#!/bin/bash
set -e

# ====================================================================
# Internal IT Portal TUG - Automated Server Update Script
# ====================================================================

APP_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$APP_DIR"

# Make sure git trusts this directory regardless of which user runs it
git config --global --add safe.directory "$APP_DIR" 2>/dev/null || true
# Ensure git connects anonymously without sending stale tokens that cause 403
git config --local credential.helper "" 2>/dev/null || true
# Disable interactive terminal prompts so git never asks for username/password
export GIT_TERMINAL_PROMPT=0

echo "==> [1/5] Pulling latest code from GitHub..."
git fetch origin main >/dev/null 2>&1 || true
git reset --hard origin/main >/dev/null 2>&1 || true

echo "==> [2/5] Installing dependencies..."
if [ ! -d "node_modules" ] || (git diff --name-only HEAD@{1} HEAD 2>/dev/null | grep -q 'package.*json'); then
  npm ci --omit=dev 2>/dev/null || npm install --omit=dev 2>/dev/null || true
else
  echo "Dependencies already up to date, skipping npm ci."
fi

echo "==> [3/5] Running database migrations..."
npm run migrate

echo "==> [4/5] Setting folder permissions..."
# Keep ownership safe for both it_ubuntu and www web server
CURRENT_USER="$(id -un 2>/dev/null || echo it_ubuntu)"
sudo chown -R "$CURRENT_USER:www" "$APP_DIR" 2>/dev/null || sudo chown -R www:www "$APP_DIR" 2>/dev/null || true
sudo chmod -R 775 "$APP_DIR" 2>/dev/null || true
sudo chmod -R 777 "$APP_DIR/.git" 2>/dev/null || true

echo "==> [5/5] Restarting application..."
# 1. Check if managed via PM2
if command -v pm2 >/dev/null 2>&1 && pm2 list 2>/dev/null | grep -q "it-portal-tug"; then
  pm2 restart it-portal-tug 2>/dev/null || true
fi

# 2. Restart via aaPanel Node.js controller (equivalent to clicking Restart in aaPanel GUI)
if [ -f /www/server/panel/pyenv/bin/python3 ]; then
  /www/server/panel/pyenv/bin/python3 -c "import sys; sys.path.append('/www/server/panel/class'); import public; from projectModel.nodejsModel import main; main().restart_project(public.to_dict_obj({'project_name': 'it-portal-tug'}))" 2>/dev/null || \
  /www/server/panel/pyenv/bin/python3 -c "import sys; sys.path.append('/www/server/panel/class'); from projectModel.nodejsModel import main; main().restart_project({'project_name': 'it-portal-tug'})" 2>/dev/null || true
fi

echo "==> All done! Portal TUG has been updated and restarted."
