#!/usr/bin/env bash
# Quant Engine CI-only hot deploy script
# Features:
#  - Shadow copy deployment (zero downtime)
#  - Automatic rollback information
#  - Deployment history tracking

set -euo pipefail

if [ "${CI_DEPLOY:-0}" != "1" ]; then
    echo "ERROR: CI-only deployment policy. Use the Gitea workflow to deploy."
    exit 1
fi

DEPLOY_BASE="/home/kjh2064/deployments"
ACTIVE_LINK="/home/kjh2064/quantengine_active"
DEPLOY_HISTORY="/home/kjh2064/.config/quantengine_deploy_history.log"
TMP_ARCHIVE="/home/kjh2064/tmp/quantengine.tar.gz"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
TARGET_DIR="${DEPLOY_BASE}/quantengine_${TIMESTAMP}"

echo "========================================="
echo "Starting Shadow Copy Hot Deploy [${TIMESTAMP}]"
echo "========================================="

mkdir -p "${DEPLOY_BASE}"
mkdir -p "${TARGET_DIR}"
mkdir -p "$(dirname "${DEPLOY_HISTORY}")"

if [ -f "${TMP_ARCHIVE}" ]; then
    echo "Extracting build artifact to ${TARGET_DIR}..."
    tar -xzf "${TMP_ARCHIVE}" -C "${TARGET_DIR}"
    rm -f "${TMP_ARCHIVE}"
else
    echo "ERROR: Deployment archive not found at ${TMP_ARCHIVE}"
    exit 1
fi

# Save previous deployment for rollback
if [ -L "${ACTIVE_LINK}" ]; then
    PREV_VERSION=$(readlink -f "${ACTIVE_LINK}")
    PREV_TIMESTAMP=$(basename "${PREV_VERSION}")
else
    PREV_VERSION="none"
    PREV_TIMESTAMP="none"
fi

echo "Previous deployment: ${PREV_VERSION}"

echo "Swapping symbolic link dynamically..."
ln -sfn "${TARGET_DIR}" "${ACTIVE_LINK}"

echo "Restarting Systemd service..."
sudo systemctl restart quantengine

# Wait for service stabilization
sleep 3

# Verify service is running
if ! systemctl is-active --quiet quantengine; then
    echo "ERROR: Service failed to start after deployment"
    echo "Rolling back to previous version: ${PREV_VERSION}"
    ln -sfn "${PREV_VERSION}" "${ACTIVE_LINK}"
    sudo systemctl restart quantengine
    exit 1
fi

echo "Recording deployment history..."
{
    echo "TIMESTAMP=${TIMESTAMP}"
    echo "COMMIT=${GIT_COMMIT:-unknown}"
    echo "DEPLOY_PATH=${TARGET_DIR}"
    echo "PREV_VERSION=${PREV_TIMESTAMP}"
    echo "STATUS=success"
    echo "DEPLOYED_AT=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
    echo "---"
} >> "${DEPLOY_HISTORY}"

echo "Cleaning up obsolete deployments..."
cd "${DEPLOY_BASE}"
ls -dt quantengine_* | tail -n +6 | while read -r old_dir; do
    echo "Removing old release: ${old_dir}"
    rm -rf "${old_dir}"
done

echo "========================================="
echo "Deployment successfully completed!"
echo "Active Version: $(readlink -f ${ACTIVE_LINK})"
echo "Previous Version (Rollback target): ${PREV_VERSION}"
echo "========================================="
