#!/usr/bin/env bash
# ===============================================================================================================
# deploy.sh - Script de despliegue de la API backend en EC2
# Descripción:
#       Despliega el artefacto .jar de la API en la EC2, gestiona backups,
#       configura el servicio systemd y ejecuta health check.
#
# Uso:
#       bash /home/thoth/deploy/setup/deploy.sh
#
# Autor: Área de Tecnología y Desarrollo - CCsoft
# ===============================================================================================================

set -euo pipefail

# -------------------------------------------------------------------------------
# Configuración
# -------------------------------------------------------------------------------
readonly APP_NAME="proyectosacc-app"
readonly ARTIFACTS_DIR="/home/thoth/deploy/artifacts"
readonly CURRENT_DIR="${ARTIFACTS_DIR}/current"
readonly BACKUP_DIR="${ARTIFACTS_DIR}/backup"
readonly LOGS_DIR="/var/log/proyectosacc/${APP_NAME}"
readonly SYSTEMD_SERVICE="${APP_NAME}.service"
readonly HEALTH_ENDPOINT="http://localhost:8080/actuator/health"
readonly MAX_RETRIES=30
readonly RETRY_INTERVAL=2

# -------------------------------------------------------------------------------
# Colores y logging
# -------------------------------------------------------------------------------
readonly CLR_RED='\033[0;31m'
readonly CLR_GREEN='\033[0;32m'
readonly CLR_YELLOW='\033[1;33m'
readonly CLR_BLUE='\033[0;34m'
readonly CLR_NC='\033[0m'

_log_info()  { echo -e "${CLR_GREEN}[INFO]${CLR_NC} $*"; }
_log_warn()  { echo -e "${CLR_YELLOW}[WARN]${CLR_NC} $*" >&2; }
_log_error() { echo -e "${CLR_RED}[ERROR]${CLR_NC} $*" >&2; }
_log_step()  { echo ""; echo -e "${CLR_BLUE}==== $* ====${CLR_NC}"; }
_fail()      { _log_error "$*"; exit 1; }

# -------------------------------------------------------------------------------
# Funciones
# -------------------------------------------------------------------------------
ensure_directories() {
    _log_step "Verificando directorios de despliegue"
    mkdir -p "${CURRENT_DIR}" "${BACKUP_DIR}" "${ARTIFACTS_DIR}/pids" "${LOGS_DIR}"
    chown -R osiris:osiris "${ARTIFACTS_DIR}"
    chmod 750 "${ARTIFACTS_DIR}"
    _log_info "Directorios listos"
}

backup_current_version() {
    _log_step "Creando backup de la versión actual"
    local current_jar="${CURRENT_DIR}/${APP_NAME}.jar"
    if [[ -f "$current_jar" ]]; then
        local timestamp
        timestamp=$(date +%Y%m%d_%H%M%S)
        local backup_name="${BACKUP_DIR}/${APP_NAME}-${timestamp}.jar"
        cp "$current_jar" "$backup_name"
        _log_info "Backup creado: ${backup_name}"
    else
        _log_warn "No hay versión actual para hacer backup"
    fi
}

stop_service() {
    _log_step "Deteniendo servicio actual"
    if systemctl is-active --quiet "${SYSTEMD_SERVICE}"; then
        sudo systemctl stop "${SYSTEMD_SERVICE}" || true
        _log_info "Servicio detenido"
    else
        _log_warn "El servicio no estaba activo"
    fi
}

create_systemd_service() {
    _log_step "Configurando servicio systemd"
    sudo tee "/etc/systemd/system/${SYSTEMD_SERVICE}" > /dev/null <<EOF
[Unit]
Description=Proyecto SACC App Service
After=network.target

[Service]
Type=simple
User=osiris
Group=osiris
WorkingDirectory=${CURRENT_DIR}
ExecStart=/usr/bin/java -jar ${CURRENT_DIR}/${APP_NAME}.jar
SuccessExitStatus=143
Restart=on-failure
RestartSec=10
StandardOutput=append:${LOGS_DIR}/${APP_NAME}-service.log
StandardError=append:${LOGS_DIR}/${APP_NAME}-service.log

[Install]
WantedBy=multi-user.target
EOF
    sudo systemctl daemon-reload
    _log_info "Servicio systemd actualizado"
}

start_service() {
    _log_step "Iniciando servicio"
    sudo systemctl enable "${SYSTEMD_SERVICE}" || true
    sudo systemctl start "${SYSTEMD_SERVICE}"
    _log_info "Servicio iniciado"
}

health_check() {
    _log_step "Ejecutando health check"
    local attempt=1
    while [[ $attempt -le $MAX_RETRIES ]]; do
        _log_info "Intento ${attempt}/${MAX_RETRIES}..."
        if curl -sf "${HEALTH_ENDPOINT}" | grep -q '"status":"UP"'; then
            _log_info "Health check PASÓ"
            return 0
        fi
        sleep "${RETRY_INTERVAL}"
        ((attempt++))
    done
    _fail "Health check FALLÓ después de ${MAX_RETRIES} intentos"
}

save_pid() {
    local pid
    pid=$(systemctl show -p MainPID --value "${SYSTEMD_SERVICE}")
    echo "$pid" > "${ARTIFACTS_DIR}/pids/${APP_NAME}.pid"
    _log_info "PID guardado: ${pid}"
}

# -------------------------------------------------------------------------------
# Main
# -------------------------------------------------------------------------------
main() {
    _log_step "Iniciando despliegue de ${APP_NAME}"
    ensure_directories
    backup_current_version
    stop_service
    create_systemd_service
    start_service
    health_check
    save_pid
    _log_info "Despliegue de ${APP_NAME} completado exitosamente"
}

main "$@"
