#!/bin/bash
# Boot Update Script: Automatically pull latest main, build, and prepare for PM2
# This script runs on LXC container boot BEFORE PM2 starts.
# It ensures the app is always up-to-date with the main branch.

set -e

APP_DIR="/root/My-Weekly-ToDo-List"
LOG_FILE="/var/log/app-boot-update.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "=== Boot update started ==="

cd "$APP_DIR"

# Check and ensure we are on main branch
log "Ensuring main branch..."
git checkout main 2>&1 | tee -a "$LOG_FILE"

# Check if there are remote changes
log "Fetching from origin..."
git fetch origin main 2>&1 | tee -a "$LOG_FILE"

LOCAL=$(git rev-parse HEAD)
REMOTE=$(git rev-parse origin/main)
NEXT_DIR="$APP_DIR/.next"

if [ "$LOCAL" = "$REMOTE" ] && [ -d "$NEXT_DIR" ]; then
    log "Already up-to-date and .next directory exists. No rebuild needed."
    log "=== Boot update finished (no changes) ==="
    exit 0
fi

if [ "$LOCAL" != "$REMOTE" ]; then
    log "Changes detected. Updating from $LOCAL to "$REMOTE""
    log "Pulling latest changes..."
    git pull origin main 2>&1 | tee -a "$LOG_FILE"
    
    log "Installing dependencies..."
    npm install 2>&1 | tee -a "$LOG_FILE"
fi

if [ ! -d "$NEXT_DIR" ] || [ "$LOCAL" != "$REMOTE" ]; then
    log "Updating database schema (Safe Migrate)..."
    npx prisma migrate deploy 2>&1 | tee -a "$LOG_FILE" || {
        log "migrate deploy failed, falling back to db push..."
        npx prisma db push --accept-data-loss 2>&1 | tee -a "$LOG_FILE"
    }

    log "Regenerating Prisma client..."
    npx prisma generate 2>&1 | tee -a "$LOG_FILE"

    log "Building application..."
    npm run build 2>&1 | tee -a "$LOG_FILE"
    
    log "Preparing standalone directory (copying static assets and env)..."
    cp -r public .next/standalone/ 2>&1 | tee -a "$LOG_FILE"
    mkdir -p .next/standalone/.next/static 2>&1 | tee -a "$LOG_FILE"
    cp -r .next/static .next/standalone/.next/ 2>&1 | tee -a "$LOG_FILE"
    cp .env .next/standalone/ 2>/dev/null || true 2>&1 | tee -a "$LOG_FILE"
fi

log "=== Boot update finished (verified/rebuilt) ==="
