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

usage() {
    cat <<'EOF'
Usage:
  rollback_billing_readiness.sh \
    --app-root /path/to/app \
    --backup-dir /path/to/backup \
    --confirm ROLLBACK_READINESS \
    [--private-config-path /home/icyla826/private_config.php]

This script restores files captured by deploy_billing_readiness.sh and removes
new files. Before rollback, close all Billing runtime gates. If the v7 migration
was applied, also execute database/migrations/2026_07_14_billing_v7_rollback_gate.sql.
EOF
}

APP_ROOT=""
BACKUP_DIR=""
CONFIRM=""
PRIVATE_CONFIG_PATH="/home/icyla826/private_config.php"

while [ "$#" -gt 0 ]; do
    case "$1" in
        --app-root)
            APP_ROOT=${2:-}
            shift 2
            ;;
        --backup-dir)
            BACKUP_DIR=${2:-}
            shift 2
            ;;
        --confirm)
            CONFIRM=${2:-}
            shift 2
            ;;
        --private-config-path)
            PRIVATE_CONFIG_PATH=${2:-}
            shift 2
            ;;
        --help|-h)
            usage
            exit 0
            ;;
        *)
            echo "Unknown argument: $1" >&2
            usage >&2
            exit 1
            ;;
    esac
done

if [ -z "$APP_ROOT" ] || [ -z "$BACKUP_DIR" ] || [ "$CONFIRM" != "ROLLBACK_READINESS" ]; then
    usage >&2
    exit 1
fi

APP_ROOT=$(cd "$APP_ROOT" 2>/dev/null && pwd) || {
    echo "Application root does not exist." >&2
    exit 1
}
BACKUP_DIR=$(cd "$BACKUP_DIR" 2>/dev/null && pwd) || {
    echo "Backup directory does not exist." >&2
    exit 1
}

if [ ! -f "$BACKUP_DIR/files-before.tar.gz" ] || [ ! -f "$BACKUP_DIR/new_files.txt" ]; then
    echo "Backup metadata is incomplete." >&2
    exit 1
fi

while IFS= read -r relative; do
    [ -n "$relative" ] || continue
    case "$relative" in
        core/private_config.php)
            echo "Refusing to remove private configuration." >&2
            exit 1
            ;;
    esac
    rm -f "$APP_ROOT/$relative"
done < "$BACKUP_DIR/new_files.txt"

tar -C "$APP_ROOT" -xzf "$BACKUP_DIR/files-before.tar.gz"

if [ ! -r "$PRIVATE_CONFIG_PATH" ]; then
    echo "External private configuration is missing after rollback." >&2
    exit 1
fi

# Versiones anteriores de core/config.php ya consultan esta variable. Se fija
# en Apache para que el rollback nunca obligue a devolver secretos al webroot.
if ! grep -q 'ICYLAB_PRIVATE_CONFIG_PATH' "$APP_ROOT/.htaccess" 2>/dev/null; then
    printf '\n<IfModule mod_env.c>\n    SetEnv ICYLAB_PRIVATE_CONFIG_PATH %s\n</IfModule>\n' "$PRIVATE_CONFIG_PATH" >> "$APP_ROOT/.htaccess"
fi

cat <<EOF
Readiness overlay rollback completed.
Application: $APP_ROOT
Database data was not restored. The v7 rollback gate SQL must be applied separately when relevant.
EOF
