#!/bin/bash
# =============================================================================
# XinfinityGroup — cPanel server-side finalization script
# -----------------------------------------------------------------------------
# Run THIS from your cPanel Terminal (or SSH) inside the app folder AFTER the
# FTP upload:   cd public_html/MX && bash deploy_remote.sh
#
# It finishes the steps that can't run over FTP:
#   1. install/refresh python packages from requirements.txt
#   2. run database migrations on the LIVE db.sqlite3
#   3. collectstatic on the server
#   4. restart Passenger by touching passenger_wsgi.py
# =============================================================================

set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"

echo "[deploy-remote] app dir: $(pwd)"

# Locate the server-created virtualenv (.venv is the cPanel Python App default)
VENV=""
for candidate in .venv venv; do
    if [ -x "$candidate/bin/python" ]; then VENV="$candidate"; break; fi
done
if [ -z "$VENV" ]; then
    echo "No virtualenv (.venv or venv) found. Create one first:"
    echo "  python3 -m venv .venv"
    exit 1
fi
PY="$(pwd)/$VENV/bin/python"
echo "[deploy-remote] using python: $PY"

echo "[deploy-remote] installing requirements…"
"$PY" -m pip install --quiet -r requirements.txt

echo "[deploy-remote] running migrations…"
DJANGO_SETTINGS_MODULE=backend.settings "$PY" manage.py migrate --noinput

echo "[deploy-remote] collecting static files…"
DJANGO_SETTINGS_MODULE=backend.settings "$PY" manage.py collectstatic --noinput --verbosity 0

echo "[deploy-remote] restarting Passenger…"
touch passenger_wsgi.py

echo "[deploy-remote] DONE."