#!/usr/bin/env bash
# ===============================================================================================================
# user-data.sh - Script de inicialización de la EC2 para proyectosacc
# Descripción:
#       Configura la instancia EC2 al primer boot: instala dependencias,
#       crea usuarios, configura Nginx como proxy de API, y prepara
#       directorios de despliegue.
#
# Autor: Área de Tecnología y Desarrollo - CCsoft
# ===============================================================================================================

set -euo pipefail

# -------------------------------------------------------------------------------
# Variables
# -------------------------------------------------------------------------------
PIPELINE_PUBLIC_KEY="${pipeline_public_key}"

# -------------------------------------------------------------------------------
# Actualizar sistema e instalar dependencias
# -------------------------------------------------------------------------------
apt-get update -y
apt-get install -y nginx openjdk-21-jdk awscli curl jq

# -------------------------------------------------------------------------------
# Crear usuarios del sistema
# -------------------------------------------------------------------------------
useradd -m -s /bin/bash thoth || true
useradd -m -s /bin/bash osiris || true

# -------------------------------------------------------------------------------
# Configurar SSH para el pipeline (usuario thoth)
# -------------------------------------------------------------------------------
mkdir -p /home/thoth/.ssh
chmod 700 /home/thoth/.ssh

echo "$PIPELINE_PUBLIC_KEY" > /home/thoth/.ssh/authorized_keys
chmod 600 /home/thoth/.ssh/authorized_keys
chown -R thoth:thoth /home/thoth/.ssh

# -------------------------------------------------------------------------------
# Crear estructura de directorios de despliegue
# -------------------------------------------------------------------------------
mkdir -p /home/thoth/deploy/artifacts/{backup,current,logs,pids}
mkdir -p /home/thoth/deploy/{scripts,setup}
chown -R thoth:thoth /home/thoth/deploy

mkdir -p /var/log/proyectosacc/proyectosacc-app
chown -R osiris:osiris /var/log/proyectosacc

# -------------------------------------------------------------------------------
# Configurar Nginx como proxy inverso SOLO para la API
# -------------------------------------------------------------------------------
cat > /etc/nginx/sites-available/proyectosacc-api <<'NGINX_EOF'
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    location /api/ {
        proxy_pass http://localhost:8080/;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    location / {
        return 404;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}
NGINX_EOF

rm -f /etc/nginx/sites-enabled/default
ln -sf /etc/nginx/sites-available/proyectosacc-api /etc/nginx/sites-enabled/proyectosacc-api

nginx -t
systemctl enable nginx
systemctl restart nginx

# -------------------------------------------------------------------------------
# Crear servicio systemd template para la API (será sobrescrito por deploy.sh)
# -------------------------------------------------------------------------------
cat > /etc/systemd/system/proyectosacc-app.service <<'SYSTEMD_EOF'
[Unit]
Description=Proyecto SACC App Service
After=network.target

[Service]
Type=simple
User=osiris
Group=osiris
WorkingDirectory=/home/thoth/deploy/artifacts/current
ExecStart=/usr/bin/java -jar /home/thoth/deploy/artifacts/current/proyectosacc-app.jar
SuccessExitStatus=143
Restart=on-failure
RestartSec=10
StandardOutput=append:/var/log/proyectosacc/proyectosacc-app/proyectosacc-app-service.log
StandardError=append:/var/log/proyectosacc/proyectosacc-app/proyectosacc-app-service.log

[Install]
WantedBy=multi-user.target
SYSTEMD_EOF

systemctl daemon-reload
systemctl enable proyectosacc-app.service || true

# -------------------------------------------------------------------------------
# Ajustar permisos finales
# -------------------------------------------------------------------------------
usermod -aG osiris thoth || true
chown -R osiris:osiris /home/thoth/deploy/artifacts
chmod 750 /home/thoth/deploy/artifacts
