#!/usr/bin/env bash
# Generate JWT token for a specific RPC container
# Usage: ./generate-jwt-token-for-container.sh <VMID> <username> [expiry_days]

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID="${1:-}"
USERNAME="${2:-rpc-user}"
EXPIRY_DAYS="${3:-365}"

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

info() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }

if [ -z "$VMID" ]; then
    error "Usage: $0 <VMID> <username> [expiry_days]"
    error "Example: $0 2503 ali-full-access 365"
    exit 1
fi

# Get JWT secret from container or saved file
JWT_SECRET=""

# Try to get from saved file first
if [ -f "/tmp/jwt_secret_${VMID}.txt" ]; then
    JWT_SECRET=$(cat "/tmp/jwt_secret_${VMID}.txt")
    info "Using saved JWT secret for VMID $VMID"
else
    # Try to get from container
    info "Retrieving JWT secret from VMID $VMID..."
    JWT_SECRET=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- cat /etc/nginx/jwt_secret 2>/dev/null" || echo "")
    
    if [ -z "$JWT_SECRET" ]; then
        error "Failed to retrieve JWT secret. Make sure JWT authentication is configured on VMID $VMID"
        error "Run: ./scripts/setup-jwt-auth-all-rpc-containers.sh first"
        exit 1
    fi
fi

# Calculate expiry time
EXPIRY=$(date -d "+${EXPIRY_DAYS} days" +%s)
NOW=$(date +%s)

# Create JWT payload
if command -v jq &> /dev/null; then
    PAYLOAD=$(jq -n \
        --arg sub "$USERNAME" \
        --arg iat "$NOW" \
        --arg exp "$EXPIRY" \
        '{sub: $sub, iat: ($iat | tonumber), exp: ($exp | tonumber)}')
else
    # Fallback without jq
    PAYLOAD="{\"sub\":\"$USERNAME\",\"iat\":$NOW,\"exp\":$EXPIRY}"
fi

# Generate token using Python
if command -v python3 &> /dev/null; then
    info "Generating JWT token using Python..."
    
    TOKEN=$(python3 <<PYTHON_SCRIPT
import hmac
import hashlib
import base64
import json
import time

def base64url_encode(data):
    return base64.urlsafe_b64encode(data).decode('utf-8').rstrip('=')

def create_jwt(payload, secret):
    header = {"alg": "HS256", "typ": "JWT"}
    
    encoded_header = base64url_encode(json.dumps(header, separators=(',', ':')).encode('utf-8'))
    encoded_payload = base64url_encode(json.dumps(payload, separators=(',', ':')).encode('utf-8'))
    
    message = f"{encoded_header}.{encoded_payload}"
    signature = hmac.new(
        secret.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    ).digest()
    encoded_signature = base64url_encode(signature)
    
    return f"{encoded_header}.{encoded_payload}.{encoded_signature}"

payload = ${PAYLOAD}
secret = '${JWT_SECRET}'
token = create_jwt(payload, secret)
print(token)
PYTHON_SCRIPT
)
    
    if [ -n "$TOKEN" ]; then
        echo ""
        info "JWT Token generated successfully!"
        echo ""
        echo "VMID: $VMID"
        echo "Username: $USERNAME"
        echo "Expiry: $EXPIRY_DAYS days"
        echo ""
        echo "Token: $TOKEN"
        echo ""
        
        # Get IP address
        declare -A RPC_IPS=(
            [2503]="192.168.11.253"
            [2504]="192.168.11.254"
            [2505]="192.168.11.255"
            [2506]="192.168.11.256"
            [2507]="192.168.11.257"
            [2508]="192.168.11.258"
        )
        
        IP="${RPC_IPS[$VMID]:-unknown}"
        
        echo "Usage:"
        echo "  curl -k -H 'Authorization: Bearer $TOKEN' \\"
        echo "    -H 'Content-Type: application/json' \\"
        echo "    -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_chainId\",\"params\":[],\"id\":1}' \\"
        echo "    https://${IP}/"
        echo ""
        exit 0
    fi
fi

error "Failed to generate JWT token. Python3 is required."
exit 1

