#!/usr/bin/env bash
# Configure Oracle Publisher Service on VMID 3500
# Usage: ./scripts/configure-oracle-publisher-service.sh [private-key]

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID=3500
PRIVATE_KEY="${1:-${DEPLOYER_PRIVATE_KEY:-}}"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

echo "========================================="
echo "Configure Oracle Publisher Service"
echo "========================================="
echo ""

# Check if private key is provided
if [ -z "$PRIVATE_KEY" ]; then
    log_warn "No private key provided"
    log_info "The service will be configured but won't start until PRIVATE_KEY is set in .env"
fi

log_info "VMID: $VMID"
log_info "Proxmox Host: $PROXMOX_HOST"
echo ""

# Test SSH connection
log_info "Testing SSH connection..."
if ! ssh -o BatchMode=yes -o ConnectTimeout=5 "root@$PROXMOX_HOST" exit 2>/dev/null; then
    log_error "SSH connection failed"
    exit 1
fi
log_success "SSH connection successful"

# Check if container exists
log_info "Checking if container $VMID exists..."
if ! ssh "root@$PROXMOX_HOST" "pct status $VMID 2>/dev/null" >/dev/null 2>&1; then
    log_error "Container $VMID does not exist"
    exit 1
fi
log_success "Container $VMID exists"
echo ""

# Fix .env file
log_info "Configuring .env file..."
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- bash" << EOF
cat > /opt/oracle-publisher/.env << 'ENVEOF'
# Oracle Publisher Configuration
RPC_URL=http://192.168.11.250:8545
WS_URL=ws://192.168.11.250:8546
CHAIN_ID=138

# Oracle Contract Addresses
AGGREGATOR_ADDRESS=0x99b3511a2d315a497c8112c1fdd8d508d4b1e506
ORACLE_ADDRESS=0x3304b747e565a97ec8ac220b0b6a1f6ffdb837e6

# Private Key (must be transmitter account)
$(if [ -n "$PRIVATE_KEY" ]; then echo "PRIVATE_KEY=$PRIVATE_KEY"; else echo "# PRIVATE_KEY=0x..."; fi)

# Update Configuration
UPDATE_INTERVAL=60
HEARTBEAT_INTERVAL=60
DEVIATION_THRESHOLD=0.5

# Data Sources (CoinGecko)
DATA_SOURCE_1_URL=https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd
DATA_SOURCE_1_PARSER=coingecko
DATA_SOURCE_2_URL=https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT
DATA_SOURCE_2_PARSER=binance

# Metrics
METRICS_PORT=8000
METRICS_ENABLED=true
ENVEOF

chown oracle:oracle /opt/oracle-publisher/.env
chmod 600 /opt/oracle-publisher/.env
echo "✓ .env file configured"
EOF

log_success ".env file configured"

# Copy oracle_publisher.py if it doesn't exist
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ORACLE_PY="$PROJECT_ROOT/smom-dbis-138/services/oracle-publisher/oracle_publisher.py"

if [ -f "$ORACLE_PY" ]; then
    log_info "Copying oracle_publisher.py..."
    scp "$ORACLE_PY" "root@$PROXMOX_HOST:/tmp/oracle_publisher.py" >/dev/null 2>&1
    ssh "root@$PROXMOX_HOST" "pct exec $VMID -- cp /tmp/oracle_publisher.py /opt/oracle-publisher/oracle_publisher.py && chown oracle:oracle /opt/oracle-publisher/oracle_publisher.py && chmod 755 /opt/oracle-publisher/oracle_publisher.py" 2>/dev/null
    log_success "oracle_publisher.py copied"
else
    log_warn "oracle_publisher.py not found at $ORACLE_PY"
fi

# Create systemd service
log_info "Creating systemd service..."
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- bash" << 'EOF'
cat > /etc/systemd/system/oracle-publisher.service << 'SERVICEEOF'
[Unit]
Description=Oracle Publisher Service
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=oracle
Group=oracle
WorkingDirectory=/opt/oracle-publisher
Environment="PATH=/opt/oracle-publisher/venv/bin:/usr/local/bin:/usr/bin:/bin"

# Load environment
EnvironmentFile=-/opt/oracle-publisher/.env

# ExecStart
ExecStart=/opt/oracle-publisher/venv/bin/python /opt/oracle-publisher/oracle_publisher.py

# Restart
Restart=always
RestartSec=10

# Security
NoNewPrivileges=true
PrivateTmp=true

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=oracle-publisher

[Install]
WantedBy=multi-user.target
SERVICEEOF

systemctl daemon-reload
echo "✓ Systemd service created"
EOF

log_success "Systemd service created"
echo ""

# Show status
log_info "Service status:"
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- systemctl status oracle-publisher.service --no-pager 2>&1 | head -15" 2>&1 || log_info "Service not running yet"

echo ""
log_success "========================================="
log_success "Configuration Complete!"
log_success "========================================="
echo ""
log_info "Next steps:"
if [ -z "$PRIVATE_KEY" ]; then
    log_warn "  1. Set PRIVATE_KEY in /opt/oracle-publisher/.env (must be transmitter account)"
fi
log_info "  2. Start service: ssh root@$PROXMOX_HOST \"pct exec $VMID -- systemctl start oracle-publisher\""
log_info "  3. Enable service: ssh root@$PROXMOX_HOST \"pct exec $VMID -- systemctl enable oracle-publisher\""
log_info "  4. Check logs: ssh root@$PROXMOX_HOST \"pct exec $VMID -- journalctl -u oracle-publisher -f\""
echo ""

