#!/bin/bash
# Daily auto-deploy script for Flutter/Go projects
# Runs at 3AM daily - no more disruptive deployments!
# Run as root/admin - no extra users needed!

set -e

# Configuration
GIT_REPO="https://lab.b0esche.cloud/b0esche/b0esche_cloud.git"
DEPLOY_DIR="/opt/auto-deploy/b0esche_cloud_rollout"
BUILD_DIR="/opt/go/data/postgres/backend/go_cloud"
LOG_FILE="/var/log/auto-deploy.log"
TIMEOUT=1800  # 30 minutes for Flutter build (increased from default)
SKIP_IF_RECENT_HOURS=2  # Skip if deployed within last 2 hours

# Logging
exec > >(tee -a "$LOG_FILE") 2>&1

# Check if we should skip deployment
LAST_DEPLOY_FILE="/tmp/last_deploy_time"
if [ -f "$LAST_DEPLOY_FILE" ]; then
    LAST_DEPLOY=$(cat "$LAST_DEPLOY_FILE")
    CURRENT_TIME=$(date +%s)
    if [ $((CURRENT_TIME - LAST_DEPLOY)) -lt $((SKIP_IF_RECENT_HOURS * 3600)) ]; then
        echo "=== Skipping deployment - recent deploy was less than $SKIP_IF_RECENT_HOURS hours ago ==="
        echo "=== Auto-deploy skipped at $(date) ==="
        exit 0
    fi
fi

echo "=== Scheduled auto-deploy started at $(date) ==="

# Create deploy directory if it doesn't exist
mkdir -p "$DEPLOY_DIR"
cd "$DEPLOY_DIR"

echo "Pulling latest changes..."
if [ -d ".git" ]; then
    git fetch origin
    git reset --hard origin/main
else
    git clone "$GIT_REPO" .
fi

echo "=== Deploying Backend ==="
# Copy backend code to build directory
echo "Copying backend code to build directory..."
mkdir -p "$BUILD_DIR"
cp -r go_cloud/* "$BUILD_DIR/"

# Build and start backend from traefik directory
cd /opt/traefik
echo "Building go-backend container..."
docker-compose build --no-cache go-backend
echo "Recreating go-backend container with fresh environment..."
docker-compose up -d --force-recreate go-backend

echo "Backend deployed successfully!"

echo "=== Deploying Frontend ==="
# Build Flutter for web with proper timeout
echo "Building Flutter web app..."
FRONTEND_DIR="$DEPLOY_DIR/b0esche_cloud"
cd "$FRONTEND_DIR"
timeout 900 sudo -u admin /opt/flutter/bin/flutter build web --release || {
    echo "Flutter build failed or timed out"
    exit 1
}

# Copy built files to nginx volume
echo "Copying built files to web server..."
rm -rf /opt/traefik/web/*
cp -r build/web/* /opt/traefik/web/

# Restart nginx container
echo "Restarting flutter-web container..."
cd /opt/traefik
docker-compose up -d --force-recreate flutter-web

echo "=== Deployment completed successfully at $(date) ==="

# Record deployment time
date +%s > "$LAST_DEPLOY_FILE"

# Health checks
echo "=== Running health checks ==="
sleep 10

if curl -f -s https://go.b0esche.cloud/health > /dev/null 2>&1; then
    echo "✅ Backend health check passed"
else
    echo "❌ Backend health check failed"
fi

if curl -f -s https://www.b0esche.cloud > /dev/null 2>&1; then
    echo "✅ Frontend health check passed"
else
    echo "❌ Frontend health check failed"
fi

echo "=== Scheduled auto-deploy completed ==="
