#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

if [ -f "$PROJECT_ROOT/.env" ]; then
    set -a
    source "$PROJECT_ROOT/.env"
    set +a
fi

REGISTRY="${REGISTRY:?REGISTRY is required}"
IMAGE_TAG="${IMAGE_TAG:?IMAGE_TAG is required}"
DEPLOY_HOST="${DEPLOY_HOST:-}"
DEPLOY_USER="${DEPLOY_USER:-deploy}"

usage() {
    echo "Usage: $0 [--rollback] [--help]"
    echo ""
    echo "Deploy Azaion.Detections to a target machine."
    echo ""
    echo "Options:"
    echo "  --rollback  Redeploy the previous image tag"
    echo "  --help      Show this help message"
    echo ""
    echo "Environment variables:"
    echo "  REGISTRY     Container registry URL (required)"
    echo "  IMAGE_TAG    Image tag to deploy (required)"
    echo "  DEPLOY_HOST  Target machine (empty = local)"
    echo "  DEPLOY_USER  SSH user (default: deploy)"
    exit 0
}

run_cmd() {
    if [ -n "$DEPLOY_HOST" ]; then
        ssh "${DEPLOY_USER}@${DEPLOY_HOST}" "$@"
    else
        eval "$@"
    fi
}

ROLLBACK=0
for arg in "$@"; do
    case "$arg" in
        --rollback) ROLLBACK=1 ;;
        --help) usage ;;
    esac
done

if [ "$ROLLBACK" -eq 1 ]; then
    PREV_TAG_FILE="$PROJECT_ROOT/.deploy-previous-tag"
    if [ ! -f "$PREV_TAG_FILE" ]; then
        echo "ERROR: No previous tag found at $PREV_TAG_FILE"
        exit 1
    fi
    IMAGE_TAG="$(cat "$PREV_TAG_FILE")"
    echo "Rolling back to image tag: $IMAGE_TAG"
fi

echo "=== Deploying Azaion.Detections ==="
echo "Registry:  $REGISTRY"
echo "Image tag: $IMAGE_TAG"
echo "Target:    ${DEPLOY_HOST:-localhost}"
echo ""

echo "--- Pulling images ---"
bash "$SCRIPT_DIR/pull-images.sh"

echo "--- Stopping services ---"
bash "$SCRIPT_DIR/stop-services.sh"

echo "--- Starting services ---"
bash "$SCRIPT_DIR/start-services.sh"

echo "--- Health check ---"
if bash "$SCRIPT_DIR/health-check.sh"; then
    echo "=== Deployment successful ==="
else
    echo "ERROR: Health check failed. Run '$0 --rollback' to revert."
    exit 1
fi
