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

# ============================================================
# SMART VISION TERMINAL UPDATER
# ============================================================

APP_ROOT='/home/CMSServer'
DOWNLOAD_URL='https://download.paco1.com/smartvision/versions/'
UPDATE_DIR="$APP_ROOT/WebServer/views/admin/settings/update/versions"
TEMP_DIR="$UPDATE_DIR/CMSServerTemp"
START_SCRIPT="$APP_ROOT/StartCMSServer.sh"
STOP_SCRIPT="$APP_ROOT/StopCMSServer.sh"
LOG_FILE="$APP_ROOT/smartvision-update.log"
LOCK_FILE='/run/lock/smartvision-update.lock'
# Smart Vision process names
PROCESSES=(
    ControlServer
    StreamServer
    FileTransferServer
    FileSaveServer
    FileMove
    HouseDog
)

# ============================================================
# SMART VISION PROCESS DETECTION
# ============================================================

# /proc/PID/comm truncates names longer than 15 characters.
is_process_running() {
    local wanted="$1" procdir exe
    for procdir in /proc/[0-9]*; do
        [[ -d "$procdir" ]] || continue
        exe=$(readlink "$procdir/exe" 2>/dev/null) || continue
        exe="${exe% (deleted)}"
        if [[ "${exe##*/}" == "$wanted" && "$exe" == "$APP_ROOT/"* ]]; then
            return 0
        fi
    done
    return 1
}

# ============================================================
# ROOT CHECK
# ============================================================

if (( EUID != 0 )); then
    echo 'ERROR: Run this updater as root.' >&2
    exit 1
fi

# ============================================================
# REQUIRED COMMANDS
# ============================================================

for cmd in \
    curl unzip php cp rm find sort grep sed tee \
    python3 readlink pgrep flock tail chmod mkdir mv sleep
do
    command -v "$cmd" >/dev/null 2>&1 || { echo "ERROR: Missing command: $cmd" >&2; exit 1; }
done
# ============================================================
# VERIFY APPLICATION
# ============================================================

[[ -d "$APP_ROOT/WebServer" ]] || { echo 'ERROR: Smart Vision installation not found.'; exit 1; }
[[ -f "$STOP_SCRIPT" && -f "$START_SCRIPT" ]] || { echo 'ERROR: Start or stop script missing.'; exit 1; }
mkdir -p "$UPDATE_DIR"

# ============================================================
# PREVENT CONCURRENT UPDATES
# ============================================================

# Keep the lock file itself; deleting a flock file is unsafe.
exec 9>"$LOCK_FILE"
if ! flock -n 9; then
    echo 'ERROR: Another Smart Vision update is running (or a prior child inherited the lock).'
    echo "Inspect with: fuser -v $LOCK_FILE"
    exit 1
fi

# ============================================================
# AUTOMATIC CLEANUP
# ============================================================

cleanup_update() {
    local rc=$?
    trap - EXIT
    if [[ -d "$TEMP_DIR" && ! -L "$TEMP_DIR" ]]; then
        echo 'Removing temporary update extraction...'
        rm -rf -- "$TEMP_DIR" || echo 'WARNING: Could not fully remove temporary extraction.'
    fi
    flock -u 9 || true
    exec 9>&-
    if (( rc != 0 )); then echo "Updater exited with status $rc."; fi
    exit "$rc"
}
trap cleanup_update EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

# ============================================================
# LOGGING
# ============================================================

# Avoid background log writer inheriting updater lock.
touch "$LOG_FILE"
exec > >(tee -a "$LOG_FILE" 9>&-) 2>&1

echo '=================================================='
echo ' SMART VISION TERMINAL UPDATER'
echo " Date: $(date)"
echo '=================================================='

# ============================================================
# FIND LATEST VERSION
# ============================================================

echo '[1/12] Checking latest Smart Vision version...'
LATEST_FILE=$(
    curl -fsSL "$DOWNLOAD_URL" |
    grep -o 'href="[^"]*' |
    sed 's/href="//' |
    grep -E '\.zip$' |
    grep -v '/' |
    LC_ALL=C sort -V |
    tail -n 1
) || true
[[ -n "$LATEST_FILE" && "$LATEST_FILE" != *'..'* && "$LATEST_FILE" != *'\\'* ]] || {
    echo 'ERROR: Unable to determine a safe latest ZIP filename.'; exit 1;
}
echo "Latest package: $LATEST_FILE"
ZIP_PATH="$UPDATE_DIR/$LATEST_FILE"

# ============================================================
# DOWNLOAD UPDATE
# ============================================================

echo '[2/12] Downloading update...'
if [[ -f "$ZIP_PATH" ]] && ! unzip -tq "$ZIP_PATH" >/dev/null 2>&1; then
    echo 'Existing ZIP is invalid; downloading again.'
    rm -f -- "$ZIP_PATH"
fi
if [[ ! -f "$ZIP_PATH" ]]; then
    PART_PATH="$ZIP_PATH.part"
    rm -f -- "$PART_PATH"
    curl -fL --retry 3 --connect-timeout 30 "$DOWNLOAD_URL$LATEST_FILE" -o "$PART_PATH"
    mv -- "$PART_PATH" "$ZIP_PATH"
fi
echo "Package ready: $ZIP_PATH"

# ============================================================
# VALIDATE ZIP
# ============================================================

echo '[3/12] Validating ZIP integrity...'
unzip -tq "$ZIP_PATH" || { echo 'ERROR: Invalid ZIP.'; exit 1; }

# ============================================================
# CHECK ZIP CONTENTS
# ============================================================

echo '[4/12] Checking ZIP contents...'
python3 - "$ZIP_PATH" <<'PY'
import sys, zipfile
from pathlib import PurePosixPath
with zipfile.ZipFile(sys.argv[1]) as z:
    for item in z.infolist():
        name = item.filename
        if not name or '\x00' in name or '\\' in name:
            raise SystemExit(f'Unsafe ZIP entry: {name!r}')
        p = PurePosixPath(name)
        if p.is_absolute() or '..' in p.parts or ':' in p.parts[0]:
            raise SystemExit(f'Unsafe ZIP path: {name}')
        mode = (item.external_attr >> 16) & 0o170000
        if mode not in (0, 0o100000, 0o040000):
            raise SystemExit(f'Unsupported ZIP entry type: {name}')
print('ZIP content validation passed.')
PY

# ============================================================
# EXTRACT UPDATE
# ============================================================

echo '[5/12] Extracting update...'
# The lock is already held; safe to discard this updater's previous staging dir.
if [[ -e "$TEMP_DIR" || -L "$TEMP_DIR" ]]; then
    echo 'Removing previous temporary extraction...'
    rm -rf -- "$TEMP_DIR"
fi
mkdir -p "$TEMP_DIR"
unzip -q "$ZIP_PATH" -d "$TEMP_DIR"
[[ -d "$TEMP_DIR/WebServer" && ! -L "$TEMP_DIR/WebServer" ]] || {
    echo 'ERROR: Invalid update structure (WebServer missing).'; exit 1;
}
if find "$TEMP_DIR" -type l -print -quit | grep -q .; then
    echo 'ERROR: Symlinks detected in extracted update.'; exit 1
fi

# ============================================================
# VALIDATE PHP FILES
# ============================================================

echo '[6/12] Validating PHP syntax...'
PHP_COUNT=0
PHP_ERRORS=0
while IFS= read -r -d '' php_file; do
    PHP_COUNT=$((PHP_COUNT + 1))
    if ! php -l "$php_file"; then
        PHP_ERRORS=$((PHP_ERRORS + 1))
    fi
done < <(find "$TEMP_DIR" -type f -iname '*.php' -print0)
# Count PHP entries in the ZIP independently of the extracted files.
# Compare file counts before modifying any live application files.
ZIP_PHP_COUNT=$(python3 - "$ZIP_PATH" <<'PYZIP'
import sys
import zipfile

with zipfile.ZipFile(sys.argv[1]) as archive:
    php_names = [
        entry.filename for entry in archive.infolist()
        if not entry.is_dir() and entry.filename.lower().endswith('.php')
    ]
    if len(php_names) != len(set(php_names)):
        raise SystemExit('ERROR: Duplicate PHP paths found in ZIP.')
    print(len(php_names))
PYZIP
)

echo "PHP files in ZIP:      $ZIP_PHP_COUNT"
echo "PHP files validated:   $PHP_COUNT"
echo "PHP syntax errors:     $PHP_ERRORS"

# ============================================================
# PHP VALIDATION WARNING
# ============================================================

if (( PHP_ERRORS > 0 || PHP_COUNT != ZIP_PHP_COUNT )); then

    echo ""
    echo "############################################################"
    echo "#                                                          #"
    echo "#               !!! CRITICAL WARNING !!!                   #"
    echo "#                                                          #"
    echo "#           SMART VISION UPDATE CANCELLED                  #"
    echo "#                                                          #"
    echo "#          PHP FILE VERIFICATION FAILED                    #"
    echo "#                                                          #"
    echo "############################################################"
    echo ""
    echo "PHP files expected:   $ZIP_PHP_COUNT"
    echo "PHP files validated:  $PHP_COUNT"
    echo "PHP syntax errors:    $PHP_ERRORS"
    echo ""
    echo "No application files have been modified."
    echo ""

    exit 1
fi

echo 'PHP file count verification: PASSED'

# ============================================================
# CONFIRM UPDATE
# ============================================================

cat <<EOF
==================================================
 UPDATE VALIDATION COMPLETED
==================================================
Package: $LATEST_FILE
PHP files in ZIP: $ZIP_PHP_COUNT
PHP files validated: $PHP_COUNT
PHP file count: MATCHED
Installation directory: $APP_ROOT

This update will preserve machine configuration and data,
stop Smart Vision, overwrite application files, run database
updates, restore executable permissions, and restart services.
Ensure you have a current backup.
EOF
read -r -p 'Type YES to install: ' CONFIRM < /dev/tty || CONFIRM=''
if [[ "$CONFIRM" != 'YES' ]]; then
    echo 'Update cancelled. No live files changed.'
    exit 0
fi

# ============================================================
# PRESERVE CONFIGURATION AND DATA
# ============================================================

echo '[7/12] Preserving configuration and runtime data...'
rm -f -- \
    "$TEMP_DIR/.env" \
    "$TEMP_DIR/WebServer/Core/config.php" \
    "$TEMP_DIR/ske.sql" \
    "$TEMP_DIR/ControlServer/ControlConfig.ini" \
    "$TEMP_DIR/FileMove/FileMoveConfig.ini" \
    "$TEMP_DIR/FileSaveServer/FileSaveConfig.ini" \
    "$TEMP_DIR/FileTransferServer/FileTransferConfig.ini" \
    "$TEMP_DIR/StreamServer/StreamConfig.ini"
rm -rf -- \
    "$TEMP_DIR/clients" \
    "$TEMP_DIR/RecordFile" \
    "$TEMP_DIR/temp" \
    "$TEMP_DIR/WebServer/images" \
    "$TEMP_DIR/WebServer/public/assets"
# Never overwrite the running updater with a file from the ZIP.
rm -f -- "$TEMP_DIR/UpdateSmartVision.sh"

# ============================================================
# STOP SMART VISION
# ============================================================

echo '[8/12] Stopping Smart Vision...'
# Close the lock FD in child processes to prevent inherited locks.
if (cd "$APP_ROOT" && bash "$STOP_SCRIPT" 9>&-); then
    echo 'Stop script finished.'
else
    echo 'WARNING: Stop script returned nonzero; verifying actual processes.'
fi
sleep 5

# ============================================================
# VERIFY SHUTDOWN
# ============================================================

echo '[9/12] Verifying Smart Vision shutdown...'
RUNNING_PROCESSES=()
for PROCESS in "${PROCESSES[@]}"; do
    if is_process_running "$PROCESS"; then
        RUNNING_PROCESSES+=("$PROCESS")
    fi
done
if (( ${#RUNNING_PROCESSES[@]} > 0 )); then
    printf 'ERROR: Still running: %s\n' "${RUNNING_PROCESSES[@]}"
    echo 'Update cancelled before copying files.'
    exit 1
fi
echo 'All monitored Smart Vision processes are stopped.'

# ============================================================
# INSTALL UPDATE
# ============================================================

echo '[10/12] Installing Smart Vision update...'

# Copy application files without preserving ZIP ownership,
# permissions, or timestamps.
#
# Existing destination files and directories generally retain
# their ownership and permissions.
#
# Protected configuration and runtime paths were removed
# from the extracted update in step 7.

if ! cp -R "$TEMP_DIR"/. "$APP_ROOT"/; then

    echo 'ERROR: File copy failed; installation may be partial.'
    echo 'Attempting to restart Smart Vision...'

    (cd "$APP_ROOT" && bash "$START_SCRIPT" 9>&-) || true

    exit 1
fi

echo 'Application files copied successfully.'

# ============================================================
# VERIFY INSTALLED FILES AND DIRECTORIES
# ============================================================

echo ""
echo "Verifying installed Smart Vision files and directories..."

if ! python3 - "$TEMP_DIR" "$APP_ROOT" <<'PYVERIFY'
import hashlib
import os
import sys
from pathlib import Path

source = Path(sys.argv[1])
destination = Path(sys.argv[2])

expected_files = 0
verified_files = 0
missing_files = 0
mismatched_files = 0

expected_dirs = 0
verified_dirs = 0
missing_dirs = 0

def sha256(path):
    digest = hashlib.sha256()

    with open(path, "rb") as file:
        for block in iter(lambda: file.read(1024 * 1024), b""):
            digest.update(block)

    return digest.hexdigest()

for root, dirs, files in os.walk(source):

    relative_root = Path(root).relative_to(source)
    destination_root = destination / relative_root

    for directory in dirs:
        expected_dirs += 1

        target = destination_root / directory

        if target.is_dir():
            verified_dirs += 1
        else:
            missing_dirs += 1
            print(f"[MISSING DIRECTORY] {target}")

    for filename in files:
        expected_files += 1

        source_file = Path(root) / filename
        destination_file = destination_root / filename

        if not destination_file.is_file():
            missing_files += 1
            print(f"[MISSING FILE] {destination_file}")
            continue

        if sha256(source_file) != sha256(destination_file):
            mismatched_files += 1
            print(f"[FILE MISMATCH] {destination_file}")
            continue

        verified_files += 1

print()
print("==================================================")
print(" SMART VISION INSTALLATION VERIFICATION")
print("==================================================")
print(f"Expected files:       {expected_files}")
print(f"Verified files:       {verified_files}")
print(f"Missing files:        {missing_files}")
print(f"Mismatched files:     {mismatched_files}")
print()
print(f"Expected directories: {expected_dirs}")
print(f"Verified directories: {verified_dirs}")
print(f"Missing directories:  {missing_dirs}")
print("==================================================")

if missing_files or mismatched_files or missing_dirs:
    print()
    print("############################################################")
    print("#                                                          #")
    print("#               !!! CRITICAL WARNING !!!                   #")
    print("#                                                          #")
    print("#         SMART VISION INSTALLATION FAILED                 #")
    print("#                                                          #")
    print("#         FILE VERIFICATION DID NOT MATCH                  #")
    print("#                                                          #")
    print("############################################################")
    print()
    print("WARNING: Application files may be partially updated.")
    print("Smart Vision will not be started automatically.")
    sys.exit(1)

print()
print("Installation verification: PASSED")
PYVERIFY
then
    echo ""
    echo "ERROR: Smart Vision installation verification failed."
    echo "Review the mismatched or missing files before restarting."
    exit 1
fi

# ZIP archives may lose Unix executable bits. Restore only known launchers/binaries.
# ============================================================
# RESTORE EXECUTABLE PERMISSIONS
# ============================================================

echo 'Restoring executable permissions...'
EXECUTABLES=(
    "$APP_ROOT/ControlServer/ControlServer"
    "$APP_ROOT/StreamServer/StreamServer"
    "$APP_ROOT/FileTransferServer/FileTransferServer"
    "$APP_ROOT/FileSaveServer/FileSaveServer"
    "$APP_ROOT/FileMove/FileMove"
    "$APP_ROOT/HouseDog/HouseDog"
)
for executable in "${EXECUTABLES[@]}"; do
    if [[ -f "$executable" ]]; then
        chmod 755 "$executable"
        echo "[755] $executable"
    else
        echo "[WARNING] Executable not found: $executable"
    fi
done
# Launcher scripts can reside in the application root or subdirectories.
find "$APP_ROOT" -type f -name 'run*.sh' -exec chmod 755 {} +
chmod 755 "$START_SCRIPT" "$STOP_SCRIPT"

# ============================================================
# MYSQL DATABASE UPDATE
# ============================================================

echo ""
echo "[11/12] Updating Smart Vision database..."
echo "Using existing Smart Vision PDO connection from main.php."

# ============================================================
# VERIFY DATABASE CONNECTION
# ============================================================

echo ""
echo "Verifying Smart Vision database connection..."

if php -d display_errors=1 -r '
    require "/home/CMSServer/WebServer/Core/main.php";

    if (!isset($pdo) || !($pdo instanceof PDO)) {
        fwrite(STDERR, "ERROR: PDO connection not available.\n");
        exit(1);
    }

    $pdo->query("SELECT 1");

    $stmt = $pdo->query("SELECT CURRENT_USER(), DATABASE()");
    $result = $stmt->fetch(PDO::FETCH_NUM);

    echo "Smart Vision database connection successful.\n";
    echo "Database user: " . $result[0] . "\n";
    echo "Database: " . $result[1] . "\n";
'; then

    echo "Database connection verified."

else

    echo ""
    echo "ERROR: Unable to connect to Smart Vision database."
    echo "Smart Vision remains stopped."

    exit 1

fi

# ============================================================
# RUN DATABASE TABLE UPDATES
# ============================================================

echo ""
echo "Running Smart Vision database table updates..."

if php \
    -d display_errors=1 \
    -d display_startup_errors=1 \
    -d log_errors=1 \
    -d error_reporting=-1 \
    -r '
        require "/home/CMSServer/WebServer/Core/main.php";
        require "/home/CMSServer/WebServer/Core/tableupdate.php";
    '; then

    echo ""
    echo "Smart Vision database updates completed successfully."

else

    UPDATE_RC=$?

    echo ""
    echo "ERROR: Smart Vision database update failed."
    echo "Exit code: $UPDATE_RC"
    echo ""
    echo "Smart Vision remains stopped."

    exit "$UPDATE_RC"

fi
# ============================================================
# START SMART VISION
# ============================================================

echo '[12/12] Starting Smart Vision...'
if ! (cd "$APP_ROOT" && bash "$START_SCRIPT" 9>&-); then
    echo 'ERROR: StartCMSServer.sh returned an error.'
    exit 1
fi
sleep 5
RUNNING_COUNT=0
for PROCESS in "${PROCESSES[@]}"; do
    if is_process_running "$PROCESS"; then
        echo "[RUNNING] $PROCESS"
        RUNNING_COUNT=$((RUNNING_COUNT + 1))
    else
        echo "[NOT FOUND] $PROCESS"
    fi
done
echo "Processes detected: $RUNNING_COUNT / ${#PROCESSES[@]}"
if (( RUNNING_COUNT != ${#PROCESSES[@]} )); then
    echo 'ERROR: Not all monitored Smart Vision services are running.'
    exit 1
fi

# ============================================================
# COMPLETE
# ============================================================

echo '=================================================='
echo ' SMART VISION UPDATE COMPLETED'
echo '=================================================='
echo "Package: $LATEST_FILE"
echo "Completed: $(date)"
echo "Log: $LOG_FILE"
echo "Downloaded ZIP preserved: $ZIP_PATH"
echo 'Temporary extraction will be removed automatically.'
