#!/bin/sh
set -eu

APP_DIR="${NFSE_APP_DIR:-/home/notanacional/www/masper-notanacional}"
PUBLIC_DIR="${NFSE_PUBLIC_DIR:-/home/notanacional/public_html}"
LOCK_DIR="$APP_DIR/.update_app.lock"
LOG_FILE="$APP_DIR/update_app.log"

log() {
  printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >> "$LOG_FILE"
}

if ! mkdir "$LOCK_DIR" 2>/dev/null; then
  log "update ignorado: lock ativo"
  exit 0
fi
trap 'rmdir "$LOCK_DIR" 2>/dev/null || true' EXIT

cd "$APP_DIR"
BEFORE="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
log "update iniciado head=$BEFORE"

git pull --ff-only >> "$LOG_FILE" 2>&1
AFTER="$(git rev-parse HEAD 2>/dev/null || echo unknown)"

CHANGED=0
if [ "$BEFORE" != "$AFTER" ] || [ "${NFSE_FORCE_DEPLOY:-0}" = "1" ]; then
  CHANGED=1
fi

if [ "$CHANGED" = "1" ]; then
  . venv/bin/activate
  if [ -f requirements-prod-py38.txt ]; then
    python -m pip install --only-binary=:all: -r requirements-prod-py38.txt >> "$LOG_FILE" 2>&1
  fi

  PYTHONPATH="$APP_DIR/src" python -m py_compile src/nf_nacional_web/*.py scripts/*.py >> "$LOG_FILE" 2>&1

  cp deploy/hostgator/index.php "$PUBLIC_DIR/index.php"
  cp deploy/hostgator/.htaccess "$PUBLIC_DIR/.htaccess"
  cp deploy/hostgator/start_panel.sh "$APP_DIR/start_panel.sh"
  cp deploy/hostgator/stop_panel.sh "$APP_DIR/stop_panel.sh"
  cp deploy/hostgator/sync_all.sh "$APP_DIR/sync_all.sh"
  chmod +x "$APP_DIR/start_panel.sh" "$APP_DIR/stop_panel.sh" "$APP_DIR/sync_all.sh"
  chmod 644 "$PUBLIC_DIR/index.php" "$PUBLIC_DIR/.htaccess"

  if [ "${NFSE_RESTART_PANEL_ON_UPDATE:-1}" = "1" ]; then
    "$APP_DIR/stop_panel.sh" >> "$LOG_FILE" 2>&1 || true
  fi
fi

"$APP_DIR/start_panel.sh" >> "$LOG_FILE" 2>&1
log "update finalizado head=$AFTER"
