#!/bin/bash

# Script de déploiement des templates admin pour SOGOMS
# Déploie uniquement les templates HTML sans recompilation

set -euo pipefail

# Configuration SSH
JUMP_USER="root"
JUMP_HOST="195.154.80.116"
JUMP_PORT="22"
JUMP_KEY="/home/pierre/.ssh/id_rsa_mbpi"

# Configuration Incus
INCUS_PROJECT="default"
INCUS_CONTAINER="gw3"

# Chemin des templates sur le container
REMOTE_TEMPLATES="/config/admin/templates"

# Couleurs
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

echo_step() { echo -e "${GREEN}==>${NC} $1"; }
echo_info() { echo -e "${BLUE}Info:${NC} $1"; }

# Répertoire du script
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
TEMPLATES_DIR="${SCRIPT_DIR}/cmd/sogoms/admin/templates"

if [ ! -d "$TEMPLATES_DIR" ]; then
    echo "Error: templates directory not found: $TEMPLATES_DIR"
    exit 1
fi

# Commandes SSH/SCP
SSH_CMD="ssh -i ${JUMP_KEY} -p ${JUMP_PORT} ${JUMP_USER}@${JUMP_HOST}"
SCP_CMD="scp -i ${JUMP_KEY} -P ${JUMP_PORT}"

# Créer archive des templates
echo_step "Creating templates archive..."
TIMESTAMP=$(date +%s)
ARCHIVE="sogoms-templates-${TIMESTAMP}.tar.gz"
tar -czf "/tmp/${ARCHIVE}" -C "${TEMPLATES_DIR}" .
echo_info "Archive: $(du -h /tmp/${ARCHIVE} | cut -f1)"

# Copier vers IN3
echo_step "Copying to jump server..."
$SCP_CMD "/tmp/${ARCHIVE}" "${JUMP_USER}@${JUMP_HOST}:/tmp/"

# Déployer sur gw3
echo_step "Deploying templates to ${INCUS_CONTAINER}..."
$SSH_CMD "
  incus project switch ${INCUS_PROJECT}
  incus file push /tmp/${ARCHIVE} ${INCUS_CONTAINER}/tmp/
  incus exec ${INCUS_CONTAINER} -- mkdir -p ${REMOTE_TEMPLATES}/partials
  incus exec ${INCUS_CONTAINER} -- tar -xzf /tmp/${ARCHIVE} -C ${REMOTE_TEMPLATES}/
  incus exec ${INCUS_CONTAINER} -- rm -f /tmp/${ARCHIVE}
  rm -f /tmp/${ARCHIVE}
  echo 'Templates deployed to ${REMOTE_TEMPLATES}'
  incus exec ${INCUS_CONTAINER} -- ls -la ${REMOTE_TEMPLATES}/
"

# Cleanup local
rm -f "/tmp/${ARCHIVE}"

echo_step "Done! Templates deployed."
echo_info "Dev mode: templates reload automatically on each request."
