#!/bin/bash

# CloudXM Build Tools - Deploy Templates to plugin.cloudxm.com.br
# Syncs template files (index.php, template.html, .htaccess) to Hostinger
#
# GitLab Variables Required:
#   - PLUGINS_HOST: SSH hostname or IP
#   - PLUGINS_USER: SSH username
#   - PLUGINS_PATH: /home/user/domains/plugin.cloudxm.com.br
#   - PLUGINS_SSH_PORT: SSH port (default: 22)
#   - PLUGINS_SSH_PRIVATE_KEY: SSH private key (file type)
#
# Usage: ./deploy-templates.sh [dry-run]

set -e

DRY_RUN="${1:-${DRY_RUN:-deploy}}"
PROJECT_PATH="$(cd "$(dirname "$0")/.." && pwd)"
TEMPLATES_DIR="$PROJECT_PATH/templates"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}i  $1${NC}"; }
log_success() { echo -e "${GREEN}+  $1${NC}"; }
log_warning() { echo -e "${YELLOW}!  $1${NC}"; }
log_error() { echo -e "${RED}x  $1${NC}"; }

echo "Deploying CloudXM plugin templates..."

if [ "$DRY_RUN" = "dry-run" ]; then
    log_warning "DRY RUN MODE - No changes will be made"
else
    log_info "LIVE DEPLOYMENT MODE"
fi

HOST="${PLUGINS_HOST}"
USER="${PLUGINS_USER}"
DEPLOY_PATH="${PLUGINS_PATH}"
PORT="${PLUGINS_SSH_PORT:-22}"
KEY="${PLUGINS_SSH_PRIVATE_KEY}"
PUBLIC_PATH="${DEPLOY_PATH}/public_html"

if [ -z "$HOST" ]; then log_error "PLUGINS_HOST is empty"; exit 1; fi
if [ -z "$USER" ]; then log_error "PLUGINS_USER is empty"; exit 1; fi
if [ -z "$DEPLOY_PATH" ]; then log_error "PLUGINS_PATH is empty"; exit 1; fi
if [ -z "$KEY" ]; then log_error "PLUGINS_SSH_PRIVATE_KEY is not configured"; exit 1; fi

log_success "Validation passed"
log_info "Target: $USER@$HOST:$PUBLIC_PATH (port $PORT)"

if [ "$DRY_RUN" = "dry-run" ]; then
    echo ""
    echo "  Files to deploy:"
    echo "    templates/index.php    -> public_html/index.php"
    echo "    templates/template.html -> public_html/template.html"
    echo "    templates/.htaccess    -> public_html/.htaccess"
    echo ""
    echo "  Files to REMOVE from server:"
    echo "    public_html/style.css  (no longer used, replaced by Tailwind CDN)"
    echo "    public_html/default.php"
    echo ""
    log_success "Dry run complete"
    exit 0
fi

eval "$(/usr/bin/ssh-agent -s)"

if [ -f "$KEY" ]; then
    KEY_FILE="$KEY"
    chmod 600 "$KEY_FILE"
else
    KEY_FILE="$(mktemp)"
    printf "%s\n" "$KEY" | tr -d '\r' > "$KEY_FILE"
    chmod 600 "$KEY_FILE"
fi

ssh-add "$KEY_FILE"
[ "$KEY_FILE" != "$KEY" ] && rm -f "$KEY_FILE"

mkdir -p ~/.ssh
chmod 700 ~/.ssh
ssh-keyscan -p "$PORT" -H "$HOST" | sort -u >> ~/.ssh/known_hosts 2>/dev/null || true

log_info "Uploading template files..."

rsync -avz --progress \
    -e "ssh -p $PORT -o StrictHostKeyChecking=no" \
    "$TEMPLATES_DIR/index.php" \
    "$TEMPLATES_DIR/template.html" \
    "$TEMPLATES_DIR/.htaccess" \
    "$USER@$HOST:$PUBLIC_PATH/"

log_info "Cleaning up old files on server..."

ssh -p "$PORT" "$USER@$HOST" "cd $PUBLIC_PATH && rm -f style.css default.php"

log_success "Templates deployed to $ENVIRONMENT"
