#!/bin/bash
#
# VitalWatch Agent - Installation Script
#
# Usage:
#   curl -fsSL https://repos.hstng.fr/install.sh | sudo bash
#

set -e

# Configuration
REPO_URL="https://repos.hstng.fr"
GPG_KEY_URL="${REPO_URL}/public.key"
KEYRING_PATH="/etc/apt/keyrings/hstng.gpg"
APT_LIST_PATH="/etc/apt/sources.list.d/hstng.list"

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

print_banner() {
    echo ""
    echo -e "${BLUE}"
    echo "  ╦  ╦┬┌┬┐┌─┐┬  ╦ ╦┌─┐┌┬┐┌─┐┬ ┬"
    echo "  ╚╗╔╝│ │ ├─┤│  ║║║├─┤ │ │  ├─┤"
    echo "   ╚╝ ┴ ┴ ┴ ┴┴─┘╚╩╝┴ ┴ ┴ └─┘┴ ┴"
    echo -e "${NC}"
    echo "  Lightweight Server Monitoring Agent"
    echo ""
}

log_info() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[!]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_step() { echo -e "${BLUE}[→]${NC} $1"; }

# Check root
if [ "$EUID" -ne 0 ]; then
    log_error "Please run as root: sudo bash install.sh"
    exit 1
fi

print_banner

# Check OS
if [ ! -f /etc/debian_version ]; then
    log_error "This script only supports Debian/Ubuntu"
    exit 1
fi

# Detect distro
if [ -f /etc/os-release ]; then
    . /etc/os-release
    DISTRO=$ID
    VERSION=$VERSION_CODENAME
    log_info "Detected: $PRETTY_NAME"
else
    DISTRO="debian"
    VERSION="bookworm"
fi

# Install dependencies
log_step "Installing dependencies..."
apt-get update -qq
apt-get install -y -qq curl apt-transport-https ca-certificates gnupg > /dev/null

# Download and install GPG key
log_step "Adding GPG key..."
mkdir -p /etc/apt/keyrings
if curl -fsSL "$GPG_KEY_URL" | gpg --dearmor -o "$KEYRING_PATH" 2>/dev/null; then
    chmod 644 "$KEYRING_PATH"
    log_info "GPG key installed"
else
    log_error "Failed to download GPG key from $GPG_KEY_URL"
    exit 1
fi

# Configure APT repository
log_step "Configuring APT repository..."
echo "deb [signed-by=${KEYRING_PATH}] ${REPO_URL} stable main" > "$APT_LIST_PATH"
log_info "APT repository configured"

# Update package list
log_step "Updating package list..."
apt-get update -qq

# Install agent
log_step "Installing vitalwatch-agent..."
apt-get install -y vitalwatch-agent

# Auto-configure if environment variables are set (for automated deployment)
if [ -n "$VITALWATCH_API_KEY" ] && [ -n "$VITALWATCH_SERVER_URL" ]; then
    log_step "Auto-configuring agent..."
    mkdir -p /etc/vitalwatch-agent
    # Remove trailing slash from URL if present
    SERVER_URL="${VITALWATCH_SERVER_URL%/}"

    cat > /etc/vitalwatch-agent/config.toml << EOF
# VitalWatch Agent Configuration
# Auto-configured by install.sh

backend_url = "${SERVER_URL}/api/v1/metrics"
api_key = "$VITALWATCH_API_KEY"

[metrics]
interval_seconds = 60
EOF
    chmod 600 /etc/vitalwatch-agent/config.toml
    log_info "Agent configured"

    log_step "Starting agent..."
    systemctl daemon-reload
    systemctl enable vitalwatch-agent
    systemctl start vitalwatch-agent
    log_info "Agent started"

    echo ""
    echo -e "${GREEN}════════════════════════════════════════${NC}"
    echo -e "${GREEN}   Installation et configuration OK !${NC}"
    echo -e "${GREEN}════════════════════════════════════════${NC}"
    echo ""
    echo -e "L'agent est maintenant connecté à: ${BLUE}$VITALWATCH_SERVER_URL${NC}"
    echo ""
    echo -e "Vérifier le statut:"
    echo -e "  ${BLUE}sudo systemctl status vitalwatch-agent${NC}"
    echo -e "  ${BLUE}sudo journalctl -u vitalwatch-agent -f${NC}"
    echo ""
    exit 0
fi

# Manual configuration instructions
echo ""
echo -e "${GREEN}════════════════════════════════════════${NC}"
echo -e "${GREEN}   Installation terminée avec succès !${NC}"
echo -e "${GREEN}════════════════════════════════════════${NC}"
echo ""
echo -e "Prochaines étapes:"
echo ""
echo -e "  ${YELLOW}1.${NC} Éditez la configuration:"
echo -e "     ${BLUE}sudo nano /etc/vitalwatch-agent/config.toml${NC}"
echo ""
echo -e "  ${YELLOW}2.${NC} Configurez votre serveur:"
echo -e "     ${BLUE}backend_url = \"https://votre-serveur.com\"${NC}"
echo -e "     ${BLUE}api_key = \"votre-clé-api\"${NC}"
echo ""
echo -e "  ${YELLOW}3.${NC} Démarrez l'agent:"
echo -e "     ${BLUE}sudo systemctl start vitalwatch-agent${NC}"
echo -e "     ${BLUE}sudo systemctl enable vitalwatch-agent${NC}"
echo ""
echo -e "  ${YELLOW}4.${NC} Vérifiez le statut:"
echo -e "     ${BLUE}sudo systemctl status vitalwatch-agent${NC}"
echo -e "     ${BLUE}sudo journalctl -u vitalwatch-agent -f${NC}"
echo ""
