#!/bin/bash
set -euo pipefail

# Proxmox Agent Setup Script

SITE="${SITE:-}"
NODE="${NODE:-}"
CLOUDFLARE_TUNNEL_TOKEN="${CLOUDFLARE_TUNNEL_TOKEN:-}"
PROMETHEUS_ENABLED="${PROMETHEUS_ENABLED:-true}"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" >&2
}

error() {
    log "ERROR: $*"
    exit 1
}

check_prerequisites() {
    if [ -z "${SITE}" ]; then
        error "SITE environment variable is required"
    fi
    
    if [ -z "${NODE}" ]; then
        error "NODE environment variable is required"
    fi
    
    if ! command -v pvesh &> /dev/null; then
        error "This script must be run on a Proxmox node"
    fi
}

install_cloudflared() {
    log "Installing cloudflared..."
    
    if command -v cloudflared &> /dev/null; then
        log "cloudflared is already installed"
        return
    fi
    
    # Download and install cloudflared
    ARCH=$(uname -m)
    case "${ARCH}" in
        x86_64)
            ARCH="amd64"
            ;;
        aarch64)
            ARCH="arm64"
            ;;
        *)
            error "Unsupported architecture: ${ARCH}"
            ;;
    esac
    
    CLOUDFLARED_VERSION="2023.10.0"
    wget -q "https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/cloudflared-linux-${ARCH}" -O /usr/local/bin/cloudflared
    chmod +x /usr/local/bin/cloudflared
    
    log "cloudflared installed successfully"
}

configure_cloudflared_tunnel() {
    log "Configuring Cloudflare tunnel..."
    
    if [ -z "${CLOUDFLARE_TUNNEL_TOKEN}" ]; then
        log "Warning: CLOUDFLARE_TUNNEL_TOKEN not set, skipping tunnel configuration"
        return
    fi
    
    # Create tunnel config directory
    mkdir -p /etc/cloudflared
    
    # Create tunnel credentials
    cat > /etc/cloudflared/${SITE}-tunnel.json <<EOF
{"AccountTag":"","TunnelSecret":"","TunnelID":"","TunnelName":"${SITE}-tunnel"}
EOF
    
    # Create systemd service
    cat > /etc/systemd/system/cloudflared-tunnel.service <<EOF
[Unit]
Description=Cloudflare Tunnel
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/cloudflared tunnel --config /etc/cloudflared/tunnel-configs/${SITE}.yaml run
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF
    
    # Copy tunnel config (should be provided separately)
    mkdir -p /etc/cloudflared/tunnel-configs
    if [ -f "../cloudflare/tunnel-configs/proxmox-${SITE}.yaml" ]; then
        cp "../cloudflare/tunnel-configs/proxmox-${SITE}.yaml" "/etc/cloudflared/tunnel-configs/${SITE}.yaml"
    else
        log "Warning: Tunnel config file not found, creating basic config..."
        cat > "/etc/cloudflared/tunnel-configs/${SITE}.yaml" <<EOF
tunnel: ${SITE}-tunnel
credentials-file: /etc/cloudflared/${SITE}-tunnel.json

ingress:
  - hostname: ${NODE}.yourdomain.com
    service: https://localhost:8006
    originRequest:
      tls:
        skipVerify: true
  - service: http_status:404
EOF
    fi
    
    systemctl daemon-reload
    systemctl enable cloudflared-tunnel.service
    systemctl start cloudflared-tunnel.service
    
    log "Cloudflare tunnel configured and started"
}

install_prometheus_exporter() {
    if [ "${PROMETHEUS_ENABLED}" != "true" ]; then
        log "Prometheus exporter disabled, skipping..."
        return
    fi
    
    log "Installing Prometheus exporter (pve_exporter)..."
    
    # Check if pve_exporter is already installed
    if command -v pve_exporter &> /dev/null; then
        log "pve_exporter is already installed"
        return
    fi
    
    # Install pve_exporter via pip or download binary
    if command -v pip3 &> /dev/null; then
        pip3 install pve_exporter
    else
        log "Warning: pip3 not found, please install pve_exporter manually"
        return
    fi
    
    # Create systemd service
    cat > /etc/systemd/system/pve-exporter.service <<EOF
[Unit]
Description=Proxmox VE Prometheus Exporter
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/pve_exporter --web.listen-address=0.0.0.0:9221
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF
    
    systemctl daemon-reload
    systemctl enable pve-exporter.service
    systemctl start pve-exporter.service
    
    log "Prometheus exporter installed and started"
}

configure_proxmox_api() {
    log "Configuring Proxmox API access..."
    
    # Create API token for Crossplane provider
    # This should be done manually or via Proxmox API
    log "Note: Create an API token in Proxmox web UI:"
    log "  Datacenter -> Permissions -> API Tokens"
    log "  Token ID: crossplane-${SITE}"
    log "  User: root@pam or dedicated service account"
    log "  Permissions: Administrator or specific VM permissions"
}

main() {
    log "Starting Proxmox agent setup for site ${SITE}, node ${NODE}..."
    
    check_prerequisites
    install_cloudflared
    configure_cloudflared_tunnel
    install_prometheus_exporter
    configure_proxmox_api
    
    log "Proxmox agent setup completed!"
    log ""
    log "Next steps:"
    log "1. Verify Cloudflare tunnel: systemctl status cloudflared-tunnel"
    log "2. Verify Prometheus exporter: curl http://localhost:9221/metrics"
    log "3. Create API token in Proxmox web UI for Crossplane provider"
}

main "$@"

