#!/usr/bin/env bash
set -Eeuo pipefail

APP_DIR="${APP_DIR:-/var/www/html/AHSP}"
PHP_BIN="${PHP_BIN:-$(command -v php || true)}"
SUDO=""

if [ "$(id -u)" -ne 0 ]; then
    SUDO="sudo"
fi

log() {
    printf '\n==> %s\n' "$*"
}

run() {
    log "$*"
    "$@"
}

run_sudo() {
    log "$SUDO $*"
    if [ -n "$SUDO" ]; then
        $SUDO "$@"
    else
        "$@"
    fi
}

artisan() {
    run "$PHP_BIN" artisan "$@"
}

if [ ! -f "$APP_DIR/artisan" ]; then
    echo "ERROR: artisan tidak ditemukan di $APP_DIR" >&2
    echo "Set APP_DIR=/path/AHSP jika lokasi project berbeda." >&2
    exit 1
fi

if [ -z "$PHP_BIN" ] || [ ! -x "$PHP_BIN" ]; then
    echo "ERROR: php binary tidak ditemukan. Set PHP_BIN=/usr/bin/php." >&2
    exit 1
fi

cd "$APP_DIR"

log "Refresh production AHSP di $APP_DIR"

artisan optimize:clear
artisan config:cache
artisan route:cache
artisan event:cache
artisan view:cache

# Tell Laravel queue workers to restart after finishing the current job.
artisan queue:restart || true

if command -v supervisorctl >/dev/null 2>&1; then
    run_sudo supervisorctl reread || true
    run_sudo supervisorctl update || true

    if $SUDO supervisorctl status "ahsp-worker-default:*" >/dev/null 2>&1; then
        run_sudo supervisorctl restart "ahsp-worker-default:*"
    fi

    if $SUDO supervisorctl status "ahsp-worker-attendance:*" >/dev/null 2>&1; then
        run_sudo supervisorctl restart "ahsp-worker-attendance:*"
    fi
fi

if command -v systemctl >/dev/null 2>&1; then
    if systemctl list-unit-files --type=service --no-legend 2>/dev/null | awk '{print $1}' | grep -Eq '^apache2\.service$'; then
        if systemctl is-active --quiet apache2; then
            run_sudo systemctl reload apache2
        fi
    fi

    if systemctl list-unit-files --type=service --no-legend 2>/dev/null | awk '{print $1}' | grep -Eq '^nginx\.service$'; then
        if systemctl is-active --quiet nginx; then
            run_sudo systemctl reload nginx
        fi
    fi

    while IFS= read -r phpFpmService; do
        [ -z "$phpFpmService" ] && continue
        if systemctl is-active --quiet "$phpFpmService"; then
            run_sudo systemctl restart "$phpFpmService"
        fi
    done < <(systemctl list-unit-files --type=service --no-legend 'php*-fpm.service' 2>/dev/null | awk '{print $1}')
fi

log "Selesai. Cek Setting > Status Server untuk verifikasi cache dan worker."
