#!/bin/bash
# cPanel deployment helper for Branch System
# ----------------------------------------
# Usage (on the cPanel server via SSH as the target cPanel user):
#   chmod +x deploy_cpanel.sh
#   ./deploy_cpanel.sh [--project-dir /home/username/path/to/app] [--venv-dir /home/username/venv]
#
# The script will:
#  - create/activate a virtualenv (in-place by default)
#  - install Python requirements
#  - run Django migrations and collectstatic
#  - run `create_default_settings` management command to ensure settings exist
#  - reload Passenger by touching `passenger_wsgi.py`

set -euo pipefail

# Default paths (can be overridden via CLI args)
PROJECT_DIR="$(pwd)"
VENV_DIR="$PROJECT_DIR/venv"
PYTHON_BIN="python3"

LOGFILE="$PROJECT_DIR/deploy_cpanel.log"

usage() {
    echo "Usage: $0 [--project-dir DIR] [--venv-dir DIR]"
    exit 1
}

# Simple arg parsing
while [[ $# -gt 0 ]]; do
  case "$1" in
    --project-dir)
      PROJECT_DIR="$2"; shift 2;;
    --venv-dir)
      VENV_DIR="$2"; shift 2;;
    -h|--help)
      usage;;
    *)
      echo "Unknown arg: $1"; usage;;
  esac
done

echo "Deploying to cPanel environment"
echo "Project dir: $PROJECT_DIR"
echo "Virtualenv dir: $VENV_DIR"
echo "Logfile: $LOGFILE"

cd "$PROJECT_DIR"

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

ensure_venv() {
  if [ ! -f "$VENV_DIR/bin/activate" ]; then
    log "Creating virtualenv at $VENV_DIR"
    $PYTHON_BIN -m venv "$VENV_DIR"
  else
    log "Using existing virtualenv at $VENV_DIR"
  fi
}

activate_venv() {
  # shellcheck disable=SC1091
  source "$VENV_DIR/bin/activate"
  pip install --upgrade pip
}

install_requirements() {
  if [ -f "requirements.txt" ]; then
    log "Installing Python requirements"
    pip install -r requirements.txt
  else
    log "No requirements.txt found, skipping pip install"
  fi
}

run_manage() {
  # Usage: run_manage "migrate --noinput"
  cmd="$1"
  log "Running: python manage.py $cmd"
  python manage.py $cmd >> "$LOGFILE" 2>&1
}

reload_passenger() {
  if [ -f "$PROJECT_DIR/passenger_wsgi.py" ]; then
    log "Touching passenger_wsgi.py to reload application"
    touch "$PROJECT_DIR/passenger_wsgi.py"
  else
    log "passenger_wsgi.py not found in project root; ensure your cPanel app uses Passenger or restart app manually"
  fi
}

# Ensure virtualenv exists and dependencies installed
ensure_venv
activate_venv
install_requirements

# Export environment variables that might be required on cPanel.
# Prefer setting these in cPanel GUI (Application Manager / Environment Variables).
# Example override: export DJANGO_SETTINGS_MODULE=branch_system.settings_production
export DJANGO_SETTINGS_MODULE=${DJANGO_SETTINGS_MODULE:-branch_system.settings_production}

# Run database migrations and collectstatic
run_manage "migrate --noinput"
run_manage "collectstatic --noinput"

# Create default settings used by the app (safe to run repeatedly)
run_manage "create_default_settings"

# Optional: create admin user if needed (will skip if exists)
run_manage "create_admin" || log "create_admin command not found or already run"

# If you have any custom post-deploy management commands, run them here
# e.g. run_manage "setup_registration_fees"

# Reload application
reload_passenger

log "cPanel deployment script completed"

echo
echo "Next steps on cPanel (if needed):"
echo " - Confirm environment variables (DB, SECRET_KEY) in cPanel Application Manager or .htaccess" 
echo " - Ensure static files are served from the collected static directory (public_html/static or similar)"
echo " - If you're using a separate media directory, ensure it's writable and configured in settings" 
echo " - Restart application manually from cPanel if needed"

exit 0
