#!/usr/bin/env bash
# Quant Engine CI-only hot deploy script

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"
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}"

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

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

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

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 "========================================="
