#!/usr/bin/env bash

set -euo pipefail

# kView INVESTOR post-deploy script for Ubuntu production servers.
#
# Usage (from anywhere):
#   ./scripts/post-deploy.sh
#
# Options:
#   --skip-maintenance   Do not toggle maintenance mode
#   --skip-migrate       Skip database migrations
#   --skip-build         Skip npm install/build
#   --skip-cache         Skip artisan config/route/view cache
#   --skip-permissions   Skip storage permission fix
#   --run-uat-smoke      Run the PostgreSQL and Passport UAT smoke after reload
#
# Environment overrides:
#   APP_DIR, PHP_BIN, WEB_USER, WEB_GROUP, NPM_BIN, FPM_SERVICE

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_DIR="${APP_DIR:-$(cd "${SCRIPT_DIR}/.." && pwd)}"
PHP_BIN="${PHP_BIN:-php}"
NPM_BIN="${NPM_BIN:-npm}"
WEB_USER="${WEB_USER:-www-data}"
WEB_GROUP="${WEB_GROUP:-www-data}"
FPM_SERVICE="${FPM_SERVICE:-php8.4-fpm}"

SKIP_MAINTENANCE=0
SKIP_MIGRATE=0
SKIP_BUILD=0
SKIP_CACHE=0
SKIP_PERMISSIONS=0
RUN_UAT_SMOKE=0

for arg in "$@"; do
    case "$arg" in
        --skip-maintenance) SKIP_MAINTENANCE=1 ;;
        --skip-migrate) SKIP_MIGRATE=1 ;;
        --skip-build) SKIP_BUILD=1 ;;
        --skip-cache) SKIP_CACHE=1 ;;
        --skip-permissions) SKIP_PERMISSIONS=1 ;;
        --run-uat-smoke) RUN_UAT_SMOKE=1 ;;
        -h|--help)
            sed -n '1,20p' "$0"
            exit 0
            ;;
        *)
            echo "Unknown option: $arg" >&2
            exit 1
            ;;
    esac
done

cd "$APP_DIR"

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

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

if [[ "$SKIP_MAINTENANCE" -eq 0 ]]; then
    log "Enabling maintenance mode"
    run_artisan down --render="errors::503" || true
fi

log "Updating git submodules"
git submodule sync --recursive
git submodule update --init --recursive

log "Installing Composer dependencies"
composer install --no-dev --optimize-autoloader --no-interaction --prefer-dist

if [[ "$SKIP_BUILD" -eq 0 ]] && command -v "$NPM_BIN" >/dev/null 2>&1; then
    log "Building frontend assets"
    if [[ -f package-lock.json ]]; then
        "$NPM_BIN" ci --no-audit --no-fund
    else
        "$NPM_BIN" install --no-audit --no-fund
    fi
    "$NPM_BIN" run build
else
    log "Skipping frontend build"
fi

if [[ "$SKIP_MIGRATE" -eq 0 ]]; then
    log "Running database migrations"
    run_artisan migrate --force --no-interaction
fi

log "Linking public storage"
run_artisan storage:link --force 2>/dev/null || run_artisan storage:link || true

if [[ "$SKIP_CACHE" -eq 0 ]]; then
    log "Refreshing Laravel caches"
    run_artisan config:clear
    run_artisan route:clear
    run_artisan view:clear
    run_artisan config:cache
    run_artisan route:cache
    run_artisan view:cache
    if run_artisan list --raw 2>/dev/null | grep -q '^event:cache$'; then
        run_artisan event:cache
    fi
fi

if [[ "$SKIP_PERMISSIONS" -eq 0 ]]; then
    log "Fixing storage permissions for ${WEB_USER}:${WEB_GROUP}"
    if [[ "$(id -u)" -ne 0 ]]; then
        sudo chown -R "${WEB_USER}:${WEB_GROUP}" storage bootstrap/cache
        sudo find storage bootstrap/cache -type d -exec chmod 775 {} \;
        sudo find storage bootstrap/cache -type f -exec chmod 664 {} \;
    else
        chown -R "${WEB_USER}:${WEB_GROUP}" storage bootstrap/cache
        find storage bootstrap/cache -type d -exec chmod 775 {} \;
        find storage bootstrap/cache -type f -exec chmod 664 {} \;
    fi
fi

if [[ "$SKIP_PERMISSIONS" -eq 0 ]]; then
    # OAuth private keys must not be readable by other users.
    if [[ "$(id -u)" -ne 0 ]]; then
        sudo find storage -maxdepth 1 -type f -name 'oauth-*.key' -exec chmod 640 {} \;
    else
        find storage -maxdepth 1 -type f -name 'oauth-*.key' -exec chmod 640 {} \;
    fi
fi

log "Restarting queue workers (if any)"
run_artisan queue:restart || true

if [[ "$SKIP_MAINTENANCE" -eq 0 ]]; then
    log "Disabling maintenance mode"
    run_artisan up
fi

if command -v systemctl >/dev/null 2>&1; then
    if systemctl list-units --type=service --all 2>/dev/null | grep -q "${FPM_SERVICE}"; then
        log "Reloading ${FPM_SERVICE}"
        if [[ "$(id -u)" -ne 0 ]]; then
            sudo systemctl reload "${FPM_SERVICE}"
        else
            systemctl reload "${FPM_SERVICE}"
        fi
    fi
fi

if [[ "$RUN_UAT_SMOKE" -eq 1 ]]; then
    log "Running UAT PostgreSQL and Passport smoke"
    run_artisan kview_investor:verify-uat --no-interaction
fi

log "Post-deploy completed successfully"
