#!/bin/bash
set -euo pipefail

NODE_ID="669427"
ENGINE_IP="10.69.69.6"
ENGINE_PORT="8301"
ORIGIN_ID="558201"
HMAC_SRC="/mnt/agents/output/build/v2/deploy/bridge_hmac.key"
NGINX_CONF="/etc/nginx/conf.d/engine-proxy.conf"
WEBROOT="/var/www/html"
PHP_DIR="/var/www/php"
HMAC_DST="${PHP_DIR}/bridge_hmac.key"
ENGINE_CLIENT_SRC="/mnt/agents/output/build/v2/deploy/EngineClient.php"

log() {
    echo "[$(date -Iseconds)] [ORIGIN] $1"
}

error_exit() {
    echo "[$(date -Iseconds)] [ORIGIN] [ERROR] $1" >&2
    exit 1
}

json_out() {
    local status="$1"
    local message="$2"
    local details="${3:-{}}"
    cat <<EOF
{
  "status": "${status}",
  "node_id": "${NODE_ID}",
  "origin_id": "${ORIGIN_ID}",
  "timestamp": "$(date -Iseconds)",
  "message": "${message}",
  "details": ${details}
}
EOF
}

if [[ "$(id -u)" -ne 0 ]]; then
    error_exit "Must run as root"
fi

if [[ ! -f /etc/os-release ]] || ! grep -q 'AlmaLinux.*9' /etc/os-release 2>/dev/null; then
    error_exit "Target must be Alma Linux 9"
fi

if [[ "$(hostname)" != *"558201"* ]] && [[ ! -f /etc/origin-node ]]; then
    log "WARNING: This does not appear to be NODE 558201 (Origin)"
    log "Continue anyway in 5 seconds (Ctrl-C to abort)..."
    sleep 5
fi

if [[ ! -f "${HMAC_SRC}" ]]; then
    log "Generating bridge HMAC key..."
    openssl rand -hex 32 > "${HMAC_SRC}"
    chmod 600 "${HMAC_SRC}"
fi

log "Installing bridge_hmac.key..."
mkdir -p "${PHP_DIR}"
cp -f "${HMAC_SRC}" "${HMAC_DST}"
chmod 640 "${HMAC_DST}"
chown nginx:nginx "${HMAC_DST}" 2>/dev/null || chown root:root "${HMAC_DST}"

log "Creating EngineClient.php..."
mkdir -p "${PHP_DIR}"
cat > "${PHP_DIR}/EngineClient.php" <<'PHPEOF'
<?php
class EngineClient {
    private string $engineUrl;
    private string $hmacKey;
    private int $timeout;

    public function __construct(
        string $engineHost = '10.69.69.6',
        int $enginePort = 8301,
        string $hmacFile = __DIR__ . '/bridge_hmac.key'
    ) {
        $this->engineUrl = "http://{$engineHost}:{$enginePort}";
        $this->hmacKey = trim(file_get_contents($hmacFile));
        $this->timeout = 10;
    }

    private function signRequest(string $body): string {
        return hash_hmac('sha256', $body, $this->hmacKey);
    }

    public function send(string $endpoint, array $payload): array {
        $body = json_encode($payload);
        $hmac = $this->signRequest($body);
        $ch = curl_init("{$this->engineUrl}{$endpoint}");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                "X-HMAC: {$hmac}",
                "X-Origin: 558201",
                "X-Timestamp: " . time()
            ],
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error) {
            return ['success' => false, 'error' => $error, 'code' => 0];
        }
        $decoded = json_decode($response, true);
        return [
            'success' => $httpCode >= 200 && $httpCode < 300,
            'code' => $httpCode,
            'body' => $decoded ?? $response
        ];
    }

    public function healthCheck(): array {
        return $this->send('/health', ['origin' => '558201', 'timestamp' => time()]);
    }

    public function processPayment(array $data): array {
        return $this->send('/api/payment/process', $data);
    }

    public function sendEmail(array $data): array {
        return $this->send('/api/email/send', $data);
    }

    public function queryOrder(string $orderId): array {
        return $this->send('/api/order/query', ['order_id' => $orderId]);
    }
}
PHPEOF
chmod 644 "${PHP_DIR}/EngineClient.php"

log "Writing nginx proxy configuration..."
cat > "${NGINX_CONF}" <<NGINXEOF
upstream engine_backend {
    server ${ENGINE_IP}:${ENGINE_PORT};
    keepalive 32;
}

server {
    listen 8443 ssl http2;
    server_name _;

    ssl_certificate /etc/nginx/ssl/origin.crt;
    ssl_certificate_key /etc/nginx/ssl/origin.key;
    ssl_protocols TLSv1.3;

    access_log /var/log/nginx/engine-access.log;
    error_log /var/log/nginx/engine-error.log;

    location /api/ {
        proxy_pass http://engine_backend;
        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-Origin-ID "558201";
        proxy_connect_timeout 10s;
        proxy_send_timeout 15s;
        proxy_read_timeout 15s;
    }

    location /health {
        proxy_pass http://engine_backend/health;
        proxy_http_version 1.1;
        proxy_connect_timeout 5s;
        proxy_read_timeout 5s;
    }

    location / {
        root ${WEBROOT};
        try_files \$uri \$uri/ =404;
    }
}
NGINXEOF
chmod 644 "${NGINX_CONF}"

mkdir -p /etc/nginx/ssl
if [[ ! -f /etc/nginx/ssl/origin.crt ]]; then
    log "Generating self-signed SSL certificate..."
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -keyout /etc/nginx/ssl/origin.key \
        -out /etc/nginx/ssl/origin.crt \
        -subj "/CN=origin-${ORIGIN_ID}" 2>/dev/null
    chmod 600 /etc/nginx/ssl/origin.key
    chmod 644 /etc/nginx/ssl/origin.crt
fi

nginx -t 2>&1 | while read line; do log "nginx: ${line}"; done || {
    error_exit "nginx configuration test failed"
}

systemctl reload nginx || systemctl restart nginx

sleep 2

log "Validating connection to ENGINE ${NODE_ID}..."
PHP_TEST=$(php -r "
require '${PHP_DIR}/EngineClient.php';
\$client = new EngineClient('${ENGINE_IP}', ${ENGINE_PORT}, '${HMAC_DST}');
\$result = \$client->healthCheck();
echo json_encode(\$result);
" 2>/dev/null)

if [[ -z "${PHP_TEST}" ]]; then
    log "WARNING: PHP health check returned empty response"
    JSON_DETAILS='{"php_check": false, "nginx": true, "note": "Engine may not be fully online yet"}'
else
    log "Health check response: ${PHP_TEST}"
    if echo "${PHP_TEST}" | grep -q '"success":[[:space:]]*true'; then
        log "Connection to ENGINE ${NODE_ID} verified"
        JSON_DETAILS="{\"php_check\": true, \"response\": ${PHP_TEST}}"
    else
        log "WARNING: Health check did not return success"
        JSON_DETAILS="{\"php_check\": false, \"response\": ${PHP_TEST}}"
    fi
fi

log "Validating systemd services..."
systemctl is-active --quiet nginx && log "nginx: running" || log "nginx: NOT running"

if systemctl is-active --quiet firewalld; then
    firewall-cmd --add-rich-rule="rule family=ipv4 destination address=${ENGINE_IP} port protocol=tcp port=${ENGINE_PORT} accept" --permanent 2>/dev/null || true
    firewall-cmd --reload
fi

log "=== Origin Update Complete ==="
json_out "success" "Origin ${ORIGIN_ID} configured for ENGINE ${NODE_ID}" "${JSON_DETAILS}"
