#!/usr/bin/env bash
#
# Cashew IMS - standalone (single-business) installer for AlmaLinux / Rocky / RHEL 8-9.
#
# Installs everything one business needs on one server, and sets up updates:
#   PHP extensions, Composer, MariaDB (if no MySQL/MariaDB yet), a database and
#   user, the app from GitHub, .env, migrations, the business + its Administrator
#   login, a PHP-FPM pool, Nginx or Apache site, firewall, Let's Encrypt SSL,
#   queue worker, scheduler cron, daily backups, and an update command.
#
# Run as root. Anything not given as an option is asked for.
#
#   sudo bash standalone-install.sh --domain sct.manabilling.com \
#        --business "Shiridinath Cashew Traders" --phone 8099144478
#
#   sudo bash standalone-install.sh --update --domain sct.manabilling.com
#
# Safe to run again: finished steps are detected and skipped (an existing .env,
# database, business and login are kept as they are).

set -Eeuo pipefail
umask 022

SCRIPT_VERSION="1.0.0"
SCRIPT_PATH=$(readlink -f "$0" 2>/dev/null || printf '%s' "$0")
# Never let ssh stop to ask a question that output redirection would hide.
export GIT_SSH_COMMAND="ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new"
DEFAULT_REPO="git@github.com:kameshvinayaka/CashewManagmentSaas.git"
STATE_DIR="/etc/cim"
REQUIRED_PHP="8.3"

# ---------------------------------------------------------------- options ---

# ======================================================= CLIENT SETTINGS ===
# Fill these in to install without being asked anything. Anything left empty
# is asked for (or uses its default). Options on the command line win.
# A filled-in copy holds passwords: keep it off GitHub, delete it from the
# server after the install.

DOMAIN="sct.manabilling.com"               # e.g. sct.manabilling.com
BUSINESS="Shiridinath Cashew Traders"             # Business name
OWNER="Admin"                # Administrator name (empty = business name)
PHONE="8099144478"                # Administrator mobile number, used to sign in
EMAIL=""                # Administrator email (optional)
PASSWORD="Kamu4tanu@"             # Administrator password (min 8 characters)

GIT_SSH_KEY=""          # Optional: private key that can read the repo; empty = root's or the sudo user's key is found automatically
GITHUB_TOKEN=""         # Optional: read-only GitHub token; used when no existing key has access
MYSQL_ADMIN_USER="root" # Only used when root cannot sign in to MySQL by itself
MYSQL_ADMIN_PASSWORD="" # Password for MYSQL_ADMIN_USER (optional)
SSL_EMAIL=""            # Email for SSL certificate notices (optional)

ASSUME_YES="yes"         # "yes" = no questions; empty settings use their defaults

# Usually left as they are.
APP_DIR="" APP_USER="" REPO="" BRANCH="main"
DB_NAME="manabilling_sct" DB_USER="manabilling_sct" DB_PASS=".H43R#3RhbDDbg?S" PHP_BIN="${PHP_BIN:-}"
SKIP_SSL="no"
# ===========================================================================

MODE="install"

usage() {
    sed -n '2,20p' "$SCRIPT_PATH" | sed 's/^# \{0,1\}//'
    cat <<'EOF'
Options:
  --domain NAME        Site address, e.g. sct.manabilling.com
  --business NAME      Business name
  --owner NAME         Owner / Administrator name
  --phone NUMBER       Administrator mobile number (used to sign in)
  --email ADDRESS      Administrator email (optional)
  --password PASS      Administrator password (asked for if left out)
  --dir PATH           Install folder (default /var/www/<domain>)
  --user NAME          Linux user that runs the app (default: first part of the domain)
  --repo URL           Git repository (default the Cashew IMS GitHub repo)
  --branch NAME        Git branch (default main)
  --db-name / --db-user / --db-pass   Use these database details instead of generated ones
  --php PATH           PHP 8.3 binary to use (default: found automatically)
  --ssl-email ADDRESS  Email for Let's Encrypt expiry notices (optional)
  --skip-ssl           Do not request an SSL certificate
  --update             Update an existing install (git pull, composer, migrate, caches)
  --yes                Accept defaults instead of asking
  -h, --help           Show this help
EOF
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --domain) DOMAIN="${2:-}"; shift 2 ;;
        --business) BUSINESS="${2:-}"; shift 2 ;;
        --owner) OWNER="${2:-}"; shift 2 ;;
        --phone) PHONE="${2:-}"; shift 2 ;;
        --email) EMAIL="${2:-}"; shift 2 ;;
        --password) PASSWORD="${2:-}"; shift 2 ;;
        --dir) APP_DIR="${2:-}"; shift 2 ;;
        --user) APP_USER="${2:-}"; shift 2 ;;
        --repo) REPO="${2:-}"; shift 2 ;;
        --branch) BRANCH="${2:-}"; shift 2 ;;
        --db-name) DB_NAME="${2:-}"; shift 2 ;;
        --db-user) DB_USER="${2:-}"; shift 2 ;;
        --db-pass) DB_PASS="${2:-}"; shift 2 ;;
        --php) PHP_BIN="${2:-}"; shift 2 ;;
        --ssl-email) SSL_EMAIL="${2:-}"; shift 2 ;;
        --skip-ssl) SKIP_SSL="yes"; shift ;;
        --update) MODE="update"; shift ;;
        --yes|-y) ASSUME_YES="yes"; shift ;;
        -h|--help) usage; exit 0 ;;
        *) echo "Unknown option: $1" >&2; usage; exit 2 ;;
    esac
done

# ---------------------------------------------------------------- output ----

LOG_FILE="/var/log/cim-standalone-install.log"
if [[ -t 1 ]]; then
    C_BOLD=$'\e[1m' C_GREEN=$'\e[32m' C_YELLOW=$'\e[33m' C_RED=$'\e[31m' C_BLUE=$'\e[34m' C_OFF=$'\e[0m'
else
    C_BOLD="" C_GREEN="" C_YELLOW="" C_RED="" C_BLUE="" C_OFF=""
fi

STEP_NO=0
step() { STEP_NO=$((STEP_NO + 1)); printf '\n%s==> [%d] %s%s\n' "$C_BOLD$C_BLUE" "$STEP_NO" "$*" "$C_OFF"; log "STEP $STEP_NO: $*"; }
ok() { printf '    %sok%s  %s\n' "$C_GREEN" "$C_OFF" "$*"; log "ok: $*"; }
info() { printf '    %s\n' "$*"; log "$*"; }
warn() { printf '    %swarning%s  %s\n' "$C_YELLOW" "$C_OFF" "$*"; log "WARNING: $*"; WARNINGS+=("$*"); }
die() { printf '\n%serror%s  %s\n' "$C_RED$C_BOLD" "$C_OFF" "$*" >&2; log "ERROR: $*"; exit 1; }
log() { [[ -w "$(dirname "$LOG_FILE")" ]] && printf '%s %s\n' "$(date '+%F %T')" "$*" >>"$LOG_FILE" || true; }
WARNINGS=()

on_error() {
    local code=$? line=$1
    printf '\n%sFailed (exit %d) at line %d:%s %s\n' "$C_RED$C_BOLD" "$code" "$line" "$C_OFF" "$BASH_COMMAND" >&2
    printf 'Full log: %s\nFix the problem and run the same command again; finished steps are skipped.\n' "$LOG_FILE" >&2
    log "FAILED exit=$code line=$line cmd=$BASH_COMMAND"
}
trap 'on_error $LINENO' ERR

# Reads an answer from the terminal; with --yes (or no terminal) the default is used.
ask() {
    local __var=$1 __question=$2 __default=${3:-} __answer=""
    if [[ "$ASSUME_YES" == "yes" || ! -r /dev/tty ]]; then
        printf -v "$__var" '%s' "$__default"
        return
    fi
    if [[ -n "$__default" ]]; then
        read -r -p "    $__question [$__default]: " __answer </dev/tty || true
    else
        read -r -p "    $__question: " __answer </dev/tty || true
    fi
    printf -v "$__var" '%s' "${__answer:-$__default}"
}

ask_secret() {
    local __var=$1 __question=$2 __answer=""
    [[ -r /dev/tty ]] || die "$__question is needed; pass it as an option (no terminal to ask on)."
    read -r -s -p "    $__question: " __answer </dev/tty || true
    printf '\n'
    printf -v "$__var" '%s' "$__answer"
}

confirm() {
    local __answer
    [[ "$ASSUME_YES" == "yes" ]] && return 0
    [[ -r /dev/tty ]] || return 0
    read -r -p "    $1 [Y/n]: " __answer </dev/tty || true
    [[ -z "$__answer" || "$__answer" =~ ^[Yy] ]]
}

random_secret() { tr -dc 'A-Za-z0-9' </dev/urandom | head -c "${1:-32}" || true; }

# Runs a command as the app user, from the app folder, with a usable HOME.
as_app() {
    runuser -u "$APP_USER" -- env HOME="$APP_HOME" COMPOSER_HOME="$APP_HOME/.composer" \
        COMPOSER_ALLOW_SUPERUSER=0 PATH="/usr/local/bin:/usr/bin:/bin" "$@"
}

# Git on the app checkout: as the app user, or as root with a GitHub key the
# server already has (root's own, or GIT_SSH_KEY such as the sudo user's).
# The files are handed back to the app user afterwards.
as_git() {
    if [[ "${GIT_AS_ROOT:-no}" == "yes" ]]; then
        if [[ -n "${GIT_SSH_KEY:-}" ]]; then
            env HOME=/root GIT_SSH_COMMAND="$(git_ssh_with_key "$GIT_SSH_KEY")" git -c safe.directory="$APP_DIR" "$@"
        else
            env HOME=/root git -c safe.directory="$APP_DIR" "$@"
        fi
    else
        as_app git "$@"
    fi
}

artisan() { (cd "$APP_DIR" && as_app "$PHP_BIN" artisan "$@"); }

# Sets KEY=value in .env (adds it when missing). Values are written as given.
env_set() {
    local key=$1 value=$2 file="$APP_DIR/.env" tmp line found=0
    tmp=$(mktemp)
    while IFS= read -r line || [[ -n "$line" ]]; do
        if [[ "$line" == "$key="* ]]; then
            printf '%s=%s\n' "$key" "$value"
            found=1
        else
            printf '%s\n' "$line"
        fi
    done <"$file" >"$tmp"
    [[ $found -eq 1 ]] || printf '%s=%s\n' "$key" "$value" >>"$tmp"
    cat "$tmp" >"$file"
    rm -f "$tmp"
}

env_get() { grep -E "^$1=" "$APP_DIR/.env" 2>/dev/null | tail -n1 | cut -d= -f2- | sed -e 's/^"//' -e 's/"$//'; }

# Quotes a value for .env (double quotes, inner quotes and backslashes escaped).
env_quote() { local v=${1//\\/\\\\}; v=${v//\"/\\\"}; v=${v//\$/\\\$}; printf '"%s"' "$v"; }

# ---------------------------------------------------------------- checks ----

preflight() {
    [[ $EUID -eq 0 ]] || die "Run as root: sudo bash $0 ..."
    cd /
    touch "$LOG_FILE" 2>/dev/null && chmod 600 "$LOG_FILE" || true
    log "---- standalone-install.sh $SCRIPT_VERSION mode=$MODE ----"

    [[ -r /etc/os-release ]] || die "Cannot read /etc/os-release; this script is for AlmaLinux / Rocky / RHEL."
    # shellcheck disable=SC1091
    . /etc/os-release
    if [[ " ${ID:-} ${ID_LIKE:-} " != *" rhel "* && " ${ID:-} ${ID_LIKE:-} " != *" fedora "* ]]; then
        die "This script is for AlmaLinux / Rocky / RHEL (found: ${PRETTY_NAME:-unknown})."
    fi
    command -v dnf >/dev/null || die "dnf not found."
    command -v systemctl >/dev/null || die "systemd not found."
    info "System: ${PRETTY_NAME:-unknown}"
}

detect_panel() {
    PANEL=""
    if [[ -d /usr/local/cpanel ]]; then PANEL="cPanel/WHM"
    elif [[ -d /usr/local/directadmin ]]; then PANEL="DirectAdmin"
    elif [[ -d /usr/local/psa ]]; then PANEL="Plesk"
    elif [[ -d /usr/local/CyberCP ]]; then PANEL="CyberPanel"
    elif [[ -d /www/server/panel ]]; then PANEL="aaPanel"
    elif [[ -d /usr/local/hestia ]]; then PANEL="HestiaCP"
    elif [[ -d /usr/local/vesta ]]; then PANEL="VestaCP"
    elif [[ -d /usr/local/lsws ]]; then PANEL="LiteSpeed"
    fi
}

# ------------------------------------------------------------- questions ----

collect_settings() {
    step "Settings"

    [[ -n "$DOMAIN" ]] || ask DOMAIN "Site address (domain)" ""
    DOMAIN=${DOMAIN,,}
    DOMAIN=${DOMAIN#http://}; DOMAIN=${DOMAIN#https://}; DOMAIN=${DOMAIN%%/*}
    [[ "$DOMAIN" =~ ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ && "$DOMAIN" == *.* ]] || die "Not a valid domain: '$DOMAIN'"

    STATE_FILE="$STATE_DIR/$DOMAIN.conf"
    if [[ -f "$STATE_FILE" ]]; then
        # Values chosen on the first run (folder, user, PHP, database names).
        # shellcheck disable=SC1090
        . "$STATE_FILE"
        info "Using saved settings from $STATE_FILE"
    elif [[ "$MODE" == "update" ]]; then
        die "No install found for $DOMAIN ($STATE_FILE missing). Run without --update first."
    fi

    local default_user
    default_user=$(printf '%s' "${DOMAIN%%.*}" | tr -cd 'a-z0-9' | cut -c1-24)
    [[ "$default_user" =~ ^[a-z] ]] || default_user="cim$default_user"

    if [[ "$MODE" == "install" ]]; then
        if [[ -n "$PANEL" && -z "${APP_DIR:-}" ]]; then
            warn "$PANEL is installed on this server. Its web server settings are managed by the panel."
            info "Create the subdomain $DOMAIN in $PANEL first, then give its Linux account and folder below."
            info "The script installs the app there and you point the subdomain's document root at <folder>/public."
        fi
        [[ -n "$APP_USER" ]] || ask APP_USER "Linux user that runs the app" "$default_user"
        [[ -n "$APP_DIR" ]] || ask APP_DIR "Install folder" "/var/www/$DOMAIN"
        [[ -n "$REPO" ]] || ask REPO "Git repository" "$DEFAULT_REPO"
        [[ -n "$BUSINESS" ]] || ask BUSINESS "Business name" ""
        [[ -n "$OWNER" ]] || ask OWNER "Owner / Administrator name" "$BUSINESS"
        [[ -n "$PHONE" ]] || ask PHONE "Administrator mobile number (used to sign in)" ""
        [[ -n "$EMAIL" ]] || ask EMAIL "Administrator email (optional, Enter to skip)" ""
        if [[ "$SKIP_SSL" != "yes" && -z "$PANEL" && -z "$SSL_EMAIL" ]]; then
            ask SSL_EMAIL "Email for SSL certificate notices (optional)" "$EMAIL"
        fi
    fi

    APP_USER=${APP_USER:-$default_user}
    APP_DIR=${APP_DIR:-/var/www/$DOMAIN}
    APP_DIR=${APP_DIR%/}
    REPO=${REPO:-$DEFAULT_REPO}
    DB_NAME=${DB_NAME:-cim_${APP_USER}}
    DB_USER=${DB_USER:-cim_${APP_USER}}
    [[ "$APP_USER" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || die "Not a valid Linux user name: '$APP_USER'"
    [[ "$DB_NAME" =~ ^[A-Za-z0-9_]{1,64}$ ]] || die "Not a valid database name: '$DB_NAME'"
    [[ "$DB_USER" =~ ^[A-Za-z0-9_]{1,32}$ ]] || die "Not a valid database user: '$DB_USER'"

    if [[ "$MODE" == "install" ]]; then
        [[ -n "$BUSINESS" ]] || die "Business name is required."
        [[ -n "$PHONE" ]] || die "Administrator mobile number is required."
        PHONE=$(printf '%s' "$PHONE" | tr -d ' -')
        [[ "$PHONE" =~ ^\+?[0-9]{6,15}$ ]] || die "Mobile number should be digits only: '$PHONE'"

        cat <<EOF

    Domain          $DOMAIN
    Business        $BUSINESS
    Administrator   ${OWNER:-$BUSINESS}  (sign in with $PHONE)
    Folder          $APP_DIR   (runs as Linux user '$APP_USER')
    Repository      $REPO  ($BRANCH)
    Database        $DB_NAME  (user $DB_USER)
    Control panel   ${PANEL:-none}

EOF
        confirm "Install with these settings?" || die "Stopped; nothing was changed."
    fi
}

save_state() {
    mkdir -p "$STATE_DIR"
    chmod 700 "$STATE_DIR"
    cat >"$STATE_FILE" <<EOF
# Written by standalone-install.sh on $(date '+%F %T'). Read again by --update.
APP_DIR=$(printf '%q' "$APP_DIR")
APP_USER=$(printf '%q' "$APP_USER")
REPO=$(printf '%q' "$REPO")
BRANCH=$(printf '%q' "$BRANCH")
DB_NAME=$(printf '%q' "$DB_NAME")
DB_USER=$(printf '%q' "$DB_USER")
PHP_BIN=$(printf '%q' "$PHP_BIN")
WEB_SERVER=$(printf '%q' "${WEB_SERVER:-}")
FPM_SERVICE=$(printf '%q' "${FPM_SERVICE:-}")
PANEL=$(printf '%q' "${PANEL:-}")
GIT_AS_ROOT=$(printf '%q' "${GIT_AS_ROOT:-no}")
GIT_SSH_KEY=$(printf '%q' "${GIT_SSH_KEY:-}")
EOF
    chmod 600 "$STATE_FILE"
}

# ------------------------------------------------------------------- php ----

find_php() {
    step "PHP $REQUIRED_PHP"
    local candidates=("$PHP_BIN" php php83 /usr/bin/php /opt/remi/php83/root/usr/bin/php
        /opt/cpanel/ea-php83/root/usr/bin/php /usr/local/lsws/lsphp83/bin/php /usr/local/php83/bin/php /www/server/php/83/bin/php)
    local candidate path version
    PHP_BIN=""
    for candidate in "${candidates[@]}"; do
        [[ -n "$candidate" ]] || continue
        path=$(command -v "$candidate" 2>/dev/null || true)
        [[ -n "$path" && -x "$path" ]] || continue
        version=$("$path" -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;' 2>/dev/null || true)
        if [[ "$version" == "$REQUIRED_PHP" ]]; then
            PHP_BIN=$path
            break
        fi
        info "Skipping $path (PHP $version)"
    done
    [[ -n "$PHP_BIN" ]] || die "PHP $REQUIRED_PHP not found. Install it (e.g. dnf module enable php:remi-8.3) or pass --php /path/to/php."
    ok "$PHP_BIN ($("$PHP_BIN" -r 'echo PHP_VERSION;'))"

    # Package name prefix for extensions, by where this PHP came from.
    case "$PHP_BIN" in
        /opt/remi/php83/*) PHP_PKG_PREFIX="php83-php-"; FPM_SERVICE="php83-php-fpm"; FPM_POOL_DIR="/etc/opt/remi/php83/php-fpm.d"; FPM_RUN_DIR="/var/opt/remi/php83/run/php-fpm"; FPM_BIN="/opt/remi/php83/root/usr/sbin/php-fpm" ;;
        /opt/cpanel/ea-php83/*) PHP_PKG_PREFIX="ea-php83-php-"; FPM_SERVICE=""; FPM_POOL_DIR=""; FPM_RUN_DIR=""; FPM_BIN="" ;;
        /usr/bin/php|/bin/php) PHP_PKG_PREFIX="php-"; FPM_SERVICE="php-fpm"; FPM_POOL_DIR="/etc/php-fpm.d"; FPM_RUN_DIR="/run/php-fpm"; FPM_BIN="/usr/sbin/php-fpm" ;;
        *) PHP_PKG_PREFIX=""; FPM_SERVICE=""; FPM_POOL_DIR=""; FPM_RUN_DIR=""; FPM_BIN="" ;;
    esac
}

php_extensions() {
    # Required by the app (gd draws the app icons; pdo_mysql talks to the database).
    local required=(ctype curl dom fileinfo filter gd mbstring openssl pdo pdo_mysql session tokenizer xml)
    local recommended=(bcmath intl zip opcache)
    local loaded missing=() missing_optional=() ext
    loaded=$("$PHP_BIN" -m 2>/dev/null | tr '[:upper:]' '[:lower:]' | sed 's/ /_/g')
    has_ext() { grep -qx "$1" <<<"$loaded" || { [[ "$1" == opcache ]] && grep -qx "zend_opcache" <<<"$loaded"; }; }
    for ext in "${required[@]}"; do has_ext "$ext" || missing+=("$ext"); done
    for ext in "${recommended[@]}"; do has_ext "$ext" || missing_optional+=("$ext"); done

    if [[ ${#missing[@]} -eq 0 && ${#missing_optional[@]} -eq 0 ]]; then
        ok "All PHP extensions present"
        return
    fi
    info "Missing PHP extensions: ${missing[*]:-} ${missing_optional[*]:-}"

    if [[ -z "$PHP_PKG_PREFIX" ]]; then
        [[ ${#missing[@]} -eq 0 ]] || die "Install these PHP extensions for $PHP_BIN, then run again: ${missing[*]}"
        warn "Recommended PHP extensions missing: ${missing_optional[*]}"
        return
    fi

    local packages=() pkg
    for ext in "${missing[@]}" "${missing_optional[@]}"; do
        case "$ext" in
            dom|xml) pkg=xml ;;
            pdo|pdo_mysql) pkg=mysqlnd ;;
            zip) pkg=pecl-zip ;;
            ctype|curl|fileinfo|filter|openssl|session|tokenizer) pkg=common ;;
            *) pkg=$ext ;;
        esac
        [[ " ${packages[*]} " == *" ${PHP_PKG_PREFIX}${pkg} "* ]] || packages+=("${PHP_PKG_PREFIX}${pkg}")
    done
    info "Installing: ${packages[*]}"
    for pkg in "${packages[@]}"; do
        dnf install -y "$pkg" >>"$LOG_FILE" 2>&1 || warn "Could not install $pkg"
    done

    loaded=$("$PHP_BIN" -m 2>/dev/null | tr '[:upper:]' '[:lower:]' | sed 's/ /_/g')
    missing=()
    for ext in "${required[@]}"; do has_ext "$ext" || missing+=("$ext"); done
    [[ ${#missing[@]} -eq 0 ]] || die "Still missing PHP extensions: ${missing[*]}. Install them for $PHP_BIN and run again."
    ok "PHP extensions installed"
}

# ----------------------------------------------------------------- tools ----

system_tools() {
    step "System tools"
    local packages=() tool
    for tool in git unzip curl tar openssl; do command -v "$tool" >/dev/null || packages+=("$tool"); done
    command -v crontab >/dev/null || packages+=(cronie)
    command -v runuser >/dev/null || packages+=(util-linux)
    if command -v getenforce >/dev/null && [[ "$(getenforce)" != "Disabled" ]]; then
        command -v semanage >/dev/null || packages+=(policycoreutils-python-utils)
    fi
    if [[ ${#packages[@]} -gt 0 ]]; then
        info "Installing: ${packages[*]}"
        dnf install -y "${packages[@]}" >>"$LOG_FILE" 2>&1 || die "dnf could not install: ${packages[*]}"
    fi
    systemctl enable --now crond >>"$LOG_FILE" 2>&1 || warn "Could not start crond (scheduler and backups need it)"
    ok "git, unzip, curl, cron ready"

    COMPOSER_BIN=$(command -v composer 2>/dev/null || true)
    if [[ -z "$COMPOSER_BIN" ]]; then
        info "Installing Composer"
        local tmp expected actual
        tmp=$(mktemp -d)
        expected=$(curl -fsSL https://composer.github.io/installer.sig)
        curl -fsSL https://getcomposer.org/installer -o "$tmp/composer-setup.php"
        actual=$("$PHP_BIN" -r "echo hash_file('sha384', '$tmp/composer-setup.php');")
        [[ "$expected" == "$actual" ]] || { rm -rf "$tmp"; die "Composer installer checksum did not match."; }
        "$PHP_BIN" "$tmp/composer-setup.php" --quiet --install-dir=/usr/local/bin --filename=composer
        rm -rf "$tmp"
        COMPOSER_BIN=/usr/local/bin/composer
    fi
    ok "Composer $("$PHP_BIN" "$COMPOSER_BIN" --version --no-ansi 2>/dev/null | awk '{print $3}')"
}

# -------------------------------------------------------------- database ----

MYSQL_ADMIN_CNF=""

database() {
    step "Database"
    local client
    client=$(command -v mariadb 2>/dev/null || command -v mysql 2>/dev/null || true)

    if [[ -z "$client" ]] || ! db_server_running; then
        if [[ -z "$client" ]]; then
            info "No MySQL/MariaDB found on this server."
        else
            info "A MySQL/MariaDB client is installed but no database server is running."
        fi
        confirm "Install MariaDB server here?" || die "A MySQL or MariaDB server is needed."
        dnf install -y mariadb-server >>"$LOG_FILE" 2>&1 || die "Could not install mariadb-server."
        systemctl enable --now mariadb >>"$LOG_FILE" 2>&1 || die "Could not start MariaDB."
        client=$(command -v mariadb 2>/dev/null || command -v mysql)
        ok "MariaDB installed and started"
    fi
    MYSQL_CLIENT=$client

    if "$MYSQL_CLIENT" --version 2>/dev/null | grep -qi mariadb || db_query_root "SELECT VERSION()" 2>/dev/null | grep -qi mariadb; then
        DB_CONNECTION=mariadb
    else
        DB_CONNECTION=mysql
    fi

    # Database password: keep the one already in .env on a re-run.
    if [[ -z "$DB_PASS" && -f "$APP_DIR/.env" ]]; then
        DB_PASS=$(env_get DB_PASSWORD)
    fi
    local generated="no"
    if [[ -z "$DB_PASS" ]]; then
        DB_PASS=$(random_secret 28)
        generated="yes"
    fi

    if db_admin_access; then
        local esc_pass=${DB_PASS//\\/\\\\}
        esc_pass=${esc_pass//\'/\\\'}
        db_query_root "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
        local host
        for host in localhost 127.0.0.1; do
            db_query_root "CREATE USER IF NOT EXISTS '$DB_USER'@'$host' IDENTIFIED BY '$esc_pass';"
            db_query_root "ALTER USER '$DB_USER'@'$host' IDENTIFIED BY '$esc_pass';"
            db_query_root "GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'$host';"
        done
        db_query_root "FLUSH PRIVILEGES;"
        ok "Database '$DB_NAME' and user '$DB_USER' ready ($DB_CONNECTION)"
    else
        [[ "$generated" == "no" ]] || {
            info "No admin access to MySQL. Create a database yourself and give its details."
            ask DB_NAME "Database name" "$DB_NAME"
            ask DB_USER "Database user" "$DB_USER"
            ask_secret DB_PASS "Database password"
        }
    fi

    # The app's own login must work before going on.
    local cnf
    cnf=$(mktemp)
    chmod 600 "$cnf"
    printf '[client]\nuser=%s\npassword="%s"\nhost=127.0.0.1\n' "$DB_USER" "${DB_PASS//\"/\\\"}" >"$cnf"
    if ! "$MYSQL_CLIENT" --defaults-extra-file="$cnf" -e "USE \`$DB_NAME\`; SELECT 1;" >/dev/null 2>>"$LOG_FILE"; then
        rm -f "$cnf"
        die "Cannot sign in to database '$DB_NAME' as '$DB_USER' on 127.0.0.1. Check the details and run again."
    fi
    rm -f "$cnf"
    ok "App can sign in to the database"
    [[ -n "$MYSQL_ADMIN_CNF" ]] && rm -f "$MYSQL_ADMIN_CNF"
    return 0
}

db_server_running() {
    local svc
    for svc in mariadb mysqld mysql; do
        systemctl is-active --quiet "$svc" 2>/dev/null && return 0
    done
    [[ -S /var/lib/mysql/mysql.sock ]] && return 0
    # cPanel and other panels may run it under another unit name.
    pgrep -x mysqld >/dev/null 2>&1 || pgrep -x mariadbd >/dev/null 2>&1
}

db_query_root() {
    if [[ -n "$MYSQL_ADMIN_CNF" ]]; then
        "$MYSQL_CLIENT" --defaults-extra-file="$MYSQL_ADMIN_CNF" -N -B -e "$1"
    else
        "$MYSQL_CLIENT" -N -B -e "$1"
    fi
}

db_admin_access() {
    # 1. root through the local socket (default on a fresh MariaDB), or /root/.my.cnf.
    if "$MYSQL_CLIENT" -N -B -e "SELECT 1" >/dev/null 2>&1; then
        ok "MySQL admin access as root"
        return 0
    fi
    # 2. The admin login from the settings, or ask for one.
    local admin_user=${MYSQL_ADMIN_USER:-root} admin_pass=${MYSQL_ADMIN_PASSWORD:-}
    if [[ -z "$admin_pass" ]]; then
        # No questions: go straight to the database details from the settings.
        if [[ "$ASSUME_YES" == "yes" ]]; then
            info "No MySQL admin login; using DB_NAME / DB_USER / DB_PASS from the settings."
            return 1
        fi
        info "MySQL needs an admin login to create the database (Enter to skip and give ready-made details)."
        ask admin_user "MySQL admin user" "$admin_user"
        ask_secret admin_pass "MySQL password for $admin_user"
    fi
    [[ -n "$admin_pass" ]] || return 1
    MYSQL_ADMIN_CNF=$(mktemp)
    chmod 600 "$MYSQL_ADMIN_CNF"
    printf '[client]\nuser=%s\npassword="%s"\n' "$admin_user" "${admin_pass//\"/\\\"}" >"$MYSQL_ADMIN_CNF"
    if "$MYSQL_CLIENT" --defaults-extra-file="$MYSQL_ADMIN_CNF" -N -B -e "SELECT 1" >/dev/null 2>&1; then
        ok "MySQL admin access as $admin_user"
        return 0
    fi
    rm -f "$MYSQL_ADMIN_CNF"
    MYSQL_ADMIN_CNF=""
    warn "That MySQL login did not work."
    return 1
}

# ------------------------------------------------------------- app user -----

app_user() {
    step "Linux user '$APP_USER'"
    if id "$APP_USER" >/dev/null 2>&1; then
        ok "User exists"
    else
        useradd --create-home --shell /sbin/nologin --comment "Cashew IMS ($DOMAIN)" "$APP_USER"
        ok "User created"
    fi
    APP_HOME=$(getent passwd "$APP_USER" | cut -d: -f6)
    [[ -n "$APP_HOME" && -d "$APP_HOME" ]] || { mkdir -p "/home/$APP_USER"; chown "$APP_USER:$APP_USER" "/home/$APP_USER"; APP_HOME="/home/$APP_USER"; }
    mkdir -p "$APP_HOME/.ssh" "$APP_HOME/.composer"
    chmod 700 "$APP_HOME/.ssh"
    chown -R "$APP_USER:$APP_USER" "$APP_HOME/.ssh" "$APP_HOME/.composer"
}

# ------------------------------------------------------------------ code ----

git_ssh_with_key() {
    printf 'ssh -i %q -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=accept-new' "$1"
}

# Private keys of root and of the user who ran sudo (e.g. the usual login user).
existing_key_files() {
    local homes=(/root) home name
    if [[ -n "${SUDO_USER:-}" && "$SUDO_USER" != root ]]; then
        home=$(getent passwd "$SUDO_USER" | cut -d: -f6)
        [[ -n "$home" ]] && homes+=("$home")
    fi
    for home in "${homes[@]}"; do
        for name in id_ed25519 id_ecdsa id_rsa; do
            [[ -f "$home/.ssh/$name" ]] && printf '%s\n' "$home/.ssh/$name"
        done
    done
    return 0
}

code_access() {
    step "Access to the code on GitHub"
    GIT_AS_ROOT=no
    if as_app git ls-remote --heads "$REPO" "$BRANCH" >/dev/null 2>&1; then
        ok "Repository reachable"
        return
    fi
    # A GitHub key this server already has: nothing to add on GitHub.
    local candidate
    for candidate in "${GIT_SSH_KEY:-}" root $(existing_key_files); do
        [[ -n "$candidate" ]] || continue
        if [[ "$candidate" == root ]]; then
            env HOME=/root git ls-remote --heads "$REPO" "$BRANCH" >/dev/null 2>&1 || continue
            GIT_SSH_KEY=""
        else
            [[ -r "$candidate" ]] || continue
            env HOME=/root GIT_SSH_COMMAND="$(git_ssh_with_key "$candidate")" git ls-remote --heads "$REPO" "$BRANCH" >/dev/null 2>&1 || continue
            GIT_SSH_KEY=$candidate
        fi
        GIT_AS_ROOT=yes
        ok "Repository reachable with this server's existing GitHub key (${GIT_SSH_KEY:-root default key})"
        return
    done
    GIT_SSH_KEY=""

    # A token in the settings: use https with it instead of a deploy key.
    if [[ -n "$GITHUB_TOKEN" && ( "$REPO" == git@github.com:* || "$REPO" == ssh://git@github.com/* ) ]]; then
        REPO="https://github.com/$(printf '%s' "$REPO" | sed -E 's#^git@github\.com:##; s#^ssh://git@github\.com/##')"
    fi

    if [[ "$REPO" == git@* || "$REPO" == ssh://* ]]; then
        local key="$APP_HOME/.ssh/id_ed25519"
        if [[ ! -f "$key" ]]; then
            as_app ssh-keygen -t ed25519 -N "" -C "$APP_USER@$DOMAIN deploy key" -f "$key" -q
        fi
        local host
        host=$(printf '%s' "$REPO" | sed -E 's#^(ssh://)?[^@]+@([^:/]+).*#\2#')
        as_app sh -c "ssh-keyscan -T 10 '$host' >> '$APP_HOME/.ssh/known_hosts' 2>/dev/null; sort -u -o '$APP_HOME/.ssh/known_hosts' '$APP_HOME/.ssh/known_hosts'"

        cat <<EOF

    This server needs read access to the private repository.
    On GitHub open the repository -> Settings -> Deploy keys -> Add deploy key,
    title "$DOMAIN", paste this key, leave "Allow write access" OFF, and save:

${C_BOLD}$(cat "$key.pub")${C_OFF}

EOF
        local tries=0
        while ! as_app git ls-remote --heads "$REPO" "$BRANCH" >/dev/null 2>>"$LOG_FILE"; do
            tries=$((tries + 1))
            # Adding the key on GitHub needs a person, so this waits even with ASSUME_YES.
            [[ -r /dev/tty && $tries -le 10 ]] || die "Still no access to $REPO. Add the deploy key above, then run again."
            read -r -p "    Press Enter after adding the key (or type 'token' to use a GitHub token instead): " answer </dev/tty || true
            if [[ "${answer:-}" == "token" ]]; then
                REPO="https://github.com/$(printf '%s' "$REPO" | sed -E 's#^git@github\.com:##; s#^ssh://git@github\.com/##')"
                code_access_token
                return
            fi
        done
    else
        code_access_token
    fi
    ok "Repository reachable"
}

code_access_token() {
    local token=$GITHUB_TOKEN
    if [[ -z "$token" ]]; then
        info "Create a fine-grained GitHub token with read-only 'Contents' access to this repository."
        ask_secret token "GitHub token"
    fi
    [[ -n "$token" ]] || die "No token given."
    local host
    host=$(printf '%s' "$REPO" | sed -E 's#^https://([^/]+)/.*#\1#')
    as_app git config --global credential.helper store
    printf 'https://x-access-token:%s@%s\n' "$token" "$host" >"$APP_HOME/.git-credentials"
    chown "$APP_USER:$APP_USER" "$APP_HOME/.git-credentials"
    chmod 600 "$APP_HOME/.git-credentials"
    as_app git ls-remote --heads "$REPO" "$BRANCH" >/dev/null 2>>"$LOG_FILE" || die "The token did not give access to $REPO."
}

fetch_code() {
    step "App code"
    if [[ -d "$APP_DIR/.git" ]]; then
        chown -R "$APP_USER:$APP_USER" "$APP_DIR"
        (cd "$APP_DIR" && as_git remote set-url origin "$REPO" && as_git fetch --quiet origin "$BRANCH" && as_git checkout --quiet "$BRANCH" && as_git merge --ff-only --quiet "origin/$BRANCH") \
            || die "Could not update the code in $APP_DIR (local changes?). Check with: cd $APP_DIR && git status"
        ok "Updated to $(cd "$APP_DIR" && as_git log -1 --format='%h %s')"
        return
    fi
    if [[ -d "$APP_DIR" && -n "$(ls -A "$APP_DIR" 2>/dev/null)" ]]; then
        die "$APP_DIR exists and is not empty. Empty it or choose another folder with --dir."
    fi
    mkdir -p "$APP_DIR"
    chown "$APP_USER:$APP_USER" "$APP_DIR"
    as_git clone --quiet --branch "$BRANCH" "$REPO" "$APP_DIR"
    chown -R "$APP_USER:$APP_USER" "$APP_DIR"
    ok "Cloned $(cd "$APP_DIR" && as_git log -1 --format='%h %s')"
}

# ------------------------------------------------------------------- app ----

write_env() {
    step "Configuration (.env)"
    local env_file="$APP_DIR/.env"
    if [[ -f "$env_file" ]]; then
        ok "Keeping existing .env"
        # Database details may have been given again on this run.
        env_set DB_CONNECTION "$DB_CONNECTION"
        env_set DB_DATABASE "$DB_NAME"
        env_set DB_USERNAME "$DB_USER"
        env_set DB_PASSWORD "$(env_quote "$DB_PASS")"
        env_set DEPLOYMENT_MODE standalone
    else
        cat >"$env_file" <<EOF
APP_NAME=$(env_quote "$BUSINESS")
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://$DOMAIN

APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file

# Single-business install (php artisan cim:install).
DEPLOYMENT_MODE=standalone
WELCOME_VARIANT=minimal
MASTER_DATA_AUTO_APPROVE=false

BCRYPT_ROUNDS=12

LOG_CHANNEL=stack
LOG_STACK=daily
LOG_DAILY_DAYS=14
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=warning

DB_CONNECTION=$DB_CONNECTION
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=$DB_NAME
DB_USERNAME=$DB_USER
DB_PASSWORD=$(env_quote "$DB_PASS")

SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
SESSION_SECURE_COOKIE=true

BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database

MAIL_MAILER=log
MAIL_FROM_ADDRESS="no-reply@$DOMAIN"
MAIL_FROM_NAME="\${APP_NAME}"

VITE_APP_NAME="\${APP_NAME}"
EOF
        ok "Written"
    fi
    chown "$APP_USER:$APP_USER" "$env_file"
    chmod 640 "$env_file"
}

install_app() {
    step "PHP packages (composer install)"
    [[ -f "$APP_DIR/public/build/manifest.json" ]] \
        || die "public/build/manifest.json is missing from the repository. Run 'npm run build' and commit public/build before installing."
    (cd "$APP_DIR" && as_app "$PHP_BIN" "$COMPOSER_BIN" install --no-dev --optimize-autoloader --no-interaction --no-progress >>"$LOG_FILE" 2>&1) \
        || die "composer install failed; see $LOG_FILE"
    ok "Installed"

    step "App setup"
    if [[ -z "$(env_get APP_KEY)" ]]; then
        artisan key:generate --force --no-interaction >>"$LOG_FILE" 2>&1
        ok "Encryption key generated (keep a copy of .env: without APP_KEY, saved logins and encrypted data cannot be read)"
    else
        ok "Encryption key already set"
    fi
    fix_permissions
    artisan config:clear --no-interaction >>"$LOG_FILE" 2>&1 || true
    artisan migrate --force --no-interaction >>"$LOG_FILE" 2>&1 || die "Migrations failed; see $LOG_FILE"
    ok "Database tables ready"
    if [[ ! -L "$APP_DIR/public/storage" ]]; then
        artisan storage:link --no-interaction >>"$LOG_FILE" 2>&1 || warn "storage:link failed"
    fi
}

create_business() {
    step "Business and Administrator login"
    local output
    if [[ -z "$PASSWORD" ]]; then
        # Only ask when the business does not exist yet.
        if business_exists; then
            ok "A business is already set up; login left unchanged"
            return
        fi
        while :; do
            ask_secret PASSWORD "Administrator password (min 8 characters)"
            local again
            ask_secret again "Same password again"
            [[ "$PASSWORD" == "$again" && ${#PASSWORD} -ge 8 ]] && break
            warn "Passwords did not match or were shorter than 8 characters."
        done
    fi
    local args=(cim:install --no-interaction "--business=$BUSINESS" "--owner=${OWNER:-$BUSINESS}" "--phone=$PHONE" "--password=$PASSWORD")
    [[ -n "$EMAIL" ]] && args+=("--email=$EMAIL")
    if output=$(artisan "${args[@]}" 2>&1); then
        ok "$(printf '%s' "$output" | tail -n1)"
    elif grep -q "already has a business" <<<"$output"; then
        ok "A business is already set up; login left unchanged"
    else
        printf '%s\n' "$output" | sed 's/^/    /'
        die "Creating the business failed."
    fi
    PASSWORD=""
}

business_exists() {
    local count
    count=$(cd "$APP_DIR" && as_app "$PHP_BIN" -r '
        require "vendor/autoload.php";
        $app = require "bootstrap/app.php";
        $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
        echo App\Models\Tenant::withTrashed()->count();' 2>/dev/null || echo 0)
    [[ "${count:-0}" -gt 0 ]]
}

fix_permissions() {
    chown -R "$APP_USER:$APP_USER" "$APP_DIR"
    find "$APP_DIR" -path "$APP_DIR/vendor" -prune -o -path "$APP_DIR/.git" -prune -o -type d -exec chmod 755 {} + 2>/dev/null || true
    chmod -R ug+rwX "$APP_DIR/storage" "$APP_DIR/bootstrap/cache"
    chmod 640 "$APP_DIR/.env"
    selinux_labels
}

selinux_labels() {
    command -v getenforce >/dev/null || return 0
    [[ "$(getenforce)" != "Disabled" ]] || return 0
    if command -v semanage >/dev/null; then
        semanage fcontext -a -t httpd_sys_content_t "$APP_DIR(/.*)?" 2>/dev/null \
            || semanage fcontext -m -t httpd_sys_content_t "$APP_DIR(/.*)?" 2>/dev/null || true
        local rw
        for rw in storage bootstrap/cache; do
            semanage fcontext -a -t httpd_sys_rw_content_t "$APP_DIR/$rw(/.*)?" 2>/dev/null \
                || semanage fcontext -m -t httpd_sys_rw_content_t "$APP_DIR/$rw(/.*)?" 2>/dev/null || true
        done
        restorecon -RF "$APP_DIR" >/dev/null 2>&1 || true
    else
        chcon -R -t httpd_sys_content_t "$APP_DIR" 2>/dev/null || true
        chcon -R -t httpd_sys_rw_content_t "$APP_DIR/storage" "$APP_DIR/bootstrap/cache" 2>/dev/null || true
    fi
    setsebool -P httpd_can_network_connect_db 1 >/dev/null 2>&1 || true
}

optimize_app() {
    artisan optimize:clear --no-interaction >>"$LOG_FILE" 2>&1 || true
    artisan optimize --no-interaction >>"$LOG_FILE" 2>&1 || die "php artisan optimize failed; see $LOG_FILE"
}

# ------------------------------------------------------------ web server ----

php_fpm_pool() {
    step "PHP-FPM pool"
    [[ -n "$FPM_SERVICE" ]] || die "Cannot tell which PHP-FPM belongs to $PHP_BIN. Set up the web server for $APP_DIR/public by hand, or use the system PHP."
    if [[ ! -x "$FPM_BIN" ]]; then
        info "Installing ${PHP_PKG_PREFIX}fpm"
        dnf install -y "${PHP_PKG_PREFIX}fpm" >>"$LOG_FILE" 2>&1 || die "Could not install ${PHP_PKG_PREFIX}fpm"
    fi
    mkdir -p "$FPM_POOL_DIR" /var/log/php-fpm
    FPM_SOCKET="$FPM_RUN_DIR/$APP_USER.sock"
    cat >"$FPM_POOL_DIR/$APP_USER.conf" <<EOF
; Managed by standalone-install.sh for $DOMAIN
[$APP_USER]
user = $APP_USER
group = $APP_USER
listen = $FPM_SOCKET
listen.owner = $WEB_USER
listen.group = $WEB_USER
listen.mode = 0660

pm = ondemand
pm.max_children = 12
pm.process_idle_timeout = 30s
pm.max_requests = 500

php_admin_value[memory_limit] = 256M
php_admin_value[upload_max_filesize] = 20M
php_admin_value[post_max_size] = 25M
php_admin_value[max_execution_time] = 120
php_admin_value[error_log] = /var/log/php-fpm/$APP_USER-error.log
php_admin_flag[log_errors] = on
php_admin_flag[expose_php] = off
EOF
    "$FPM_BIN" -t >>"$LOG_FILE" 2>&1 || die "PHP-FPM config test failed; see $LOG_FILE"
    systemctl enable "$FPM_SERVICE" >>"$LOG_FILE" 2>&1 || true
    systemctl restart "$FPM_SERVICE" >>"$LOG_FILE" 2>&1 || die "Could not restart $FPM_SERVICE"
    for _ in 1 2 3 4 5; do [[ -S "$FPM_SOCKET" ]] && break; sleep 1; done
    [[ -S "$FPM_SOCKET" ]] || die "PHP-FPM socket $FPM_SOCKET did not appear."
    ok "Pool '$APP_USER' on $FPM_SOCKET ($FPM_SERVICE)"
}

detect_web_server() {
    WEB_SERVER=""
    if systemctl is-active --quiet nginx 2>/dev/null; then WEB_SERVER=nginx
    elif systemctl is-active --quiet httpd 2>/dev/null; then WEB_SERVER=httpd
    elif command -v nginx >/dev/null; then WEB_SERVER=nginx
    elif command -v httpd >/dev/null; then WEB_SERVER=httpd
    fi
    if [[ -z "$WEB_SERVER" ]]; then
        info "No web server found; installing Nginx"
        dnf install -y nginx >>"$LOG_FILE" 2>&1 || die "Could not install nginx."
        WEB_SERVER=nginx
    fi
    if [[ "$WEB_SERVER" == nginx ]]; then WEB_USER=nginx; else WEB_USER=apache; fi
    id "$WEB_USER" >/dev/null 2>&1 || die "Web server user '$WEB_USER' not found."
}

# Writes a site file, keeping a backup of one this script did not write.
write_site_file() {
    local file=$1 content=$2
    if [[ -f "$file" ]] && ! grep -q "Managed by standalone-install.sh" "$file"; then
        cp -a "$file" "$file.bak-$(date +%Y%m%d%H%M%S)"
        warn "Backed up existing $file"
    fi
    # certbot adds its SSL lines to this file; keep them on a re-run.
    if [[ -f "$file" ]] && grep -q "managed by Certbot" "$file"; then
        ok "Site file already has SSL from certbot; left as it is"
        return 1
    fi
    printf '%s\n' "$content" >"$file"
}

web_server() {
    step "Web server ($WEB_SERVER)"
    local others domain_re=${DOMAIN//./\\.}
    others=$(grep -rlsE "server_name[^;]*[[:space:]]${domain_re}[[:space:];]|ServerName[[:space:]]+${domain_re}\$" /etc/nginx/conf.d /etc/httpd/conf.d 2>/dev/null | grep -v "/$DOMAIN.conf$" || true)
    [[ -z "$others" ]] || warn "Other site files also mention $DOMAIN: $others"

    if [[ "$WEB_SERVER" == nginx ]]; then
        SITE_FILE="/etc/nginx/conf.d/$DOMAIN.conf"
        write_site_file "$SITE_FILE" "# Managed by standalone-install.sh for $DOMAIN
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN;
    root $APP_DIR/public;
    index index.php;
    charset utf-8;
    client_max_body_size 25M;

    add_header X-Frame-Options \"SAMEORIGIN\";
    add_header X-Content-Type-Options \"nosniff\";

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    location /build/ {
        expires 1y;
        access_log off;
        try_files \$uri =404;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ ^/index\\.php(/|\$) {
        fastcgi_pass unix:$FPM_SOCKET;
        fastcgi_param SCRIPT_FILENAME \$realpath_root\$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
        fastcgi_read_timeout 120;
    }

    location ~ /\\.(?!well-known).* {
        deny all;
    }

    access_log /var/log/nginx/$DOMAIN.access.log;
    error_log /var/log/nginx/$DOMAIN.error.log;
}" || true
        nginx -t >>"$LOG_FILE" 2>&1 || die "nginx config test failed (nginx -t); see $LOG_FILE"
    else
        SITE_FILE="/etc/httpd/conf.d/$DOMAIN.conf"
        write_site_file "$SITE_FILE" "# Managed by standalone-install.sh for $DOMAIN
<VirtualHost *:80>
    ServerName $DOMAIN
    DocumentRoot $APP_DIR/public

    <Directory $APP_DIR/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <FilesMatch \\.php\$>
        SetHandler \"proxy:unix:$FPM_SOCKET|fcgi://$APP_USER-fpm\"
    </FilesMatch>

    LimitRequestBody 26214400
    ErrorLog /var/log/httpd/$DOMAIN-error.log
    CustomLog /var/log/httpd/$DOMAIN-access.log combined
</VirtualHost>" || true
        apachectl configtest >>"$LOG_FILE" 2>&1 || die "Apache config test failed (apachectl configtest); see $LOG_FILE"
    fi
    systemctl enable "$WEB_SERVER" >>"$LOG_FILE" 2>&1 || true
    if systemctl is-active --quiet "$WEB_SERVER"; then
        systemctl reload "$WEB_SERVER"
    else
        systemctl start "$WEB_SERVER" || die "Could not start $WEB_SERVER"
    fi
    ok "Site $DOMAIN -> $APP_DIR/public"

    if systemctl is-active --quiet firewalld 2>/dev/null; then
        firewall-cmd --permanent --add-service=http --add-service=https >/dev/null 2>&1 || true
        firewall-cmd --reload >/dev/null 2>&1 || true
        ok "Firewall: http and https open"
    fi
}

ssl_certificate() {
    step "SSL certificate (Let's Encrypt)"
    SSL_OK="no"
    if [[ "$SKIP_SSL" == "yes" ]]; then
        warn "Skipped (--skip-ssl). The site runs on http until a certificate is added."
        return
    fi
    if certbot certificates 2>/dev/null | grep -qE "Domains:.*[[:space:]]$DOMAIN([[:space:]]|$)"; then
        SSL_OK="yes"
        ok "Certificate already exists"
        return
    fi

    local dns_ips
    dns_ips=$(getent ahostsv4 "$DOMAIN" 2>/dev/null | awk '{print $1}' | sort -u | tr '\n' ' ')
    if [[ -z "$dns_ips" ]]; then
        warn "$DOMAIN does not resolve yet. Add a DNS A record pointing to this server, then run this script again for SSL."
        return
    fi
    info "$DOMAIN points to: $dns_ips"

    local plugin_pkg=python3-certbot-nginx
    [[ "$WEB_SERVER" == httpd ]] && plugin_pkg="python3-certbot-apache mod_ssl"
    if ! command -v certbot >/dev/null || ! rpm -q "${plugin_pkg%% *}" >/dev/null 2>&1; then
        rpm -q epel-release >/dev/null 2>&1 || dnf install -y epel-release >>"$LOG_FILE" 2>&1 || true
        # shellcheck disable=SC2086
        dnf install -y certbot $plugin_pkg >>"$LOG_FILE" 2>&1 || { warn "Could not install certbot; site stays on http."; return; }
    fi

    local email_args=(--register-unsafely-without-email)
    [[ -n "$SSL_EMAIL" ]] && email_args=(-m "$SSL_EMAIL")
    local plugin=--nginx
    [[ "$WEB_SERVER" == httpd ]] && plugin=--apache
    if certbot "$plugin" -d "$DOMAIN" --non-interactive --agree-tos --redirect "${email_args[@]}" >>"$LOG_FILE" 2>&1; then
        SSL_OK="yes"
        systemctl enable --now certbot-renew.timer >>"$LOG_FILE" 2>&1 || true
        ok "Certificate issued; http redirects to https; renews automatically"
    else
        warn "Let's Encrypt could not issue a certificate (DNS not pointing here yet, or port 80 blocked). See $LOG_FILE. Site stays on http; run this script again later."
    fi
}

# Points APP_URL and the session cookie at https only when a certificate exists.
finalize_url() {
    if [[ "${SSL_OK:-no}" == "yes" || -n "$PANEL" ]]; then
        env_set APP_URL "https://$DOMAIN"
        env_set SESSION_SECURE_COOKIE true
    else
        env_set APP_URL "http://$DOMAIN"
        env_set SESSION_SECURE_COOKIE false
    fi
}

# ---------------------------------------------------- background services ---

background_services() {
    step "Queue worker, scheduler and backups"
    local unit="cim-$APP_USER-queue"
    cat >"/etc/systemd/system/$unit.service" <<EOF
# Managed by standalone-install.sh for $DOMAIN
[Unit]
Description=Cashew IMS queue worker ($DOMAIN)
After=network.target mariadb.service mysqld.service

[Service]
User=$APP_USER
Group=$APP_USER
WorkingDirectory=$APP_DIR
ExecStart=$PHP_BIN $APP_DIR/artisan queue:work --sleep=3 --tries=3 --max-time=3600
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable "$unit" >>"$LOG_FILE" 2>&1
    systemctl restart "$unit"
    ok "Queue worker: systemctl status $unit"

    cat >"/etc/cron.d/cim-$APP_USER" <<EOF
# Managed by standalone-install.sh for $DOMAIN
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
* * * * * $APP_USER cd $APP_DIR && $PHP_BIN artisan schedule:run >> /dev/null 2>&1
30 2 * * * root /usr/local/sbin/cim-$APP_USER-backup >> /var/log/cim-$APP_USER-backup.log 2>&1
EOF
    chmod 644 "/etc/cron.d/cim-$APP_USER"
    ok "Scheduler runs every minute"

    BACKUP_DIR="/var/backups/cim/$APP_USER"
    mkdir -p "$BACKUP_DIR"
    chmod 700 "$BACKUP_DIR"
    local cnf="$STATE_DIR/$APP_USER.my.cnf"
    printf '[client]\nuser=%s\npassword="%s"\nhost=127.0.0.1\n' "$DB_USER" "${DB_PASS//\"/\\\"}" >"$cnf"
    chmod 600 "$cnf"
    local dump
    dump=$(command -v mariadb-dump 2>/dev/null || command -v mysqldump 2>/dev/null || echo mysqldump)
    cat >"/usr/local/sbin/cim-$APP_USER-backup" <<EOF
#!/usr/bin/env bash
# Managed by standalone-install.sh for $DOMAIN: database + uploaded files + .env, kept 14 days.
set -euo pipefail
stamp=\$(date +%Y%m%d-%H%M)
dir=$BACKUP_DIR
$dump --defaults-extra-file=$cnf --single-transaction --quick --routines --no-tablespaces $DB_NAME | gzip -9 > "\$dir/db-\$stamp.sql.gz"
tar -czf "\$dir/files-\$stamp.tar.gz" -C $APP_DIR .env storage/app 2>/dev/null || true
chmod 600 "\$dir"/*-"\$stamp".*
find "\$dir" -type f -mtime +14 -delete
echo "\$(date '+%F %T') backup \$stamp done"
EOF
    chmod 700 "/usr/local/sbin/cim-$APP_USER-backup"
    if "/usr/local/sbin/cim-$APP_USER-backup" >>"$LOG_FILE" 2>&1; then
        ok "Daily backup at 02:30 to $BACKUP_DIR (first one taken now)"
    else
        warn "First backup failed; see $LOG_FILE"
    fi

    # The update command runs a copy of this script kept on the server.
    refresh_script_copy
    cat >"/usr/local/sbin/cim-$APP_USER-update" <<EOF
#!/usr/bin/env bash
exec /usr/local/sbin/cim-standalone --update --domain $DOMAIN "\$@"
EOF
    chmod 700 "/usr/local/sbin/cim-$APP_USER-update"
    ok "Update command: cim-$APP_USER-update"
}

# Copies the newest standalone-install.sh (from the app checkout) to
# /usr/local/sbin/cim-standalone. Rename, not overwrite: bash reads a running
# script as it goes, so the file in use must never change under it.
refresh_script_copy() {
    local source="$APP_DIR/standalone-install.sh"
    [[ -f "$source" ]] || source="$SCRIPT_PATH"
    [[ -f "$source" ]] || { warn "No copy of this script to keep for updates."; return 0; }
    local tmp
    tmp=$(mktemp /usr/local/sbin/.cim-standalone.XXXXXX)
    # Never keep the passwords from a filled-in settings block.
    sed -E 's/^(PASSWORD|GITHUB_TOKEN|MYSQL_ADMIN_PASSWORD)="[^"]*"/\1=""/' "$source" >"$tmp"
    chmod 700 "$tmp"
    mv -f "$tmp" /usr/local/sbin/cim-standalone
}

# ----------------------------------------------------------------- checks ---

health_check() {
    step "Check"
    local code url
    if [[ "${SSL_OK:-no}" == "yes" ]]; then
        url="https://$DOMAIN/login"
        code=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 20 --resolve "$DOMAIN:443:127.0.0.1" "$url" || true)
    else
        url="http://$DOMAIN/login"
        code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 --resolve "$DOMAIN:80:127.0.0.1" "$url" || true)
    fi
    if [[ "$code" == "200" ]]; then
        ok "Sign-in page answers ($url -> $code)"
    else
        warn "Sign-in page answered $code ($url). Check storage/logs in $APP_DIR and /var/log/$WEB_SERVER."
    fi
}

# ------------------------------------------------------------------ flows ---

run_install() {
    preflight
    detect_panel
    collect_settings
    find_php
    php_extensions
    system_tools
    app_user
    database
    save_state
    code_access
    fetch_code
    write_env
    install_app
    create_business

    if [[ -z "$PANEL" ]]; then
        detect_web_server
        php_fpm_pool
        web_server
        save_state
        ssl_certificate
    else
        step "Web server"
        warn "Web server not changed ($PANEL manages it). In $PANEL set the document root of $DOMAIN to $APP_DIR/public, use PHP 8.3, and issue SSL there."
        info "The panel's PHP must run as '$APP_USER' or be able to write $APP_DIR/storage and $APP_DIR/bootstrap/cache."
    fi

    save_state
    finalize_url
    fix_permissions
    optimize_app
    background_services
    [[ -n "$PANEL" ]] || health_check

    local url
    url=$(env_get APP_URL)
    cat <<EOF

${C_BOLD}${C_GREEN}Installed.${C_OFF}

    Open           $url/login
    Sign in with   $PHONE  (the Administrator password you set)
    App folder     $APP_DIR      (runs as '$APP_USER')
    Settings       $APP_DIR/.env   -- keep a copy somewhere safe
    Backups        ${BACKUP_DIR:-}  (daily 02:30, kept 14 days)
    Update later   sudo cim-$APP_USER-update
    Install log    $LOG_FILE
EOF
    if [[ ${#WARNINGS[@]} -gt 0 ]]; then
        printf '\n    %sNeeds attention:%s\n' "$C_YELLOW" "$C_OFF"
        printf '      - %s\n' "${WARNINGS[@]}"
    fi
}

run_update() {
    preflight
    detect_panel
    collect_settings
    [[ -d "$APP_DIR/.git" ]] || die "$APP_DIR is not a git checkout."
    APP_HOME=$(getent passwd "$APP_USER" | cut -d: -f6)
    COMPOSER_BIN=$(command -v composer 2>/dev/null || echo /usr/local/bin/composer)
    [[ -x "$PHP_BIN" ]] || find_php

    step "Backup before update"
    if [[ -x "/usr/local/sbin/cim-$APP_USER-backup" ]]; then
        "/usr/local/sbin/cim-$APP_USER-backup" >>"$LOG_FILE" 2>&1 && ok "Backup taken" || die "Backup failed; update stopped. See $LOG_FILE"
    else
        warn "No backup command found; continuing without a backup."
    fi

    local before
    before=$(cd "$APP_DIR" && as_git rev-parse --short HEAD)
    artisan down --retry=30 --no-interaction >>"$LOG_FILE" 2>&1 || true
    trap 'artisan up --no-interaction >/dev/null 2>&1 || true' EXIT

    fetch_code
    install_app
    fix_permissions
    optimize_app
    artisan queue:restart --no-interaction >>"$LOG_FILE" 2>&1 || true
    if [[ -n "${FPM_SERVICE:-}" ]]; then
        systemctl reload "$FPM_SERVICE" >>"$LOG_FILE" 2>&1 || true
    fi
    artisan up --no-interaction >>"$LOG_FILE" 2>&1
    trap - EXIT
    refresh_script_copy

    local after
    after=$(cd "$APP_DIR" && as_git rev-parse --short HEAD)
    printf '\n%sUpdated%s %s -> %s\n' "$C_BOLD$C_GREEN" "$C_OFF" "$before" "$after"
}

if [[ "$MODE" == "update" ]]; then
    run_update
else
    run_install
fi
