#!/bin/bash
# Add IP address to operator whitelist

set -e

if [ $# -lt 2 ]; then
    echo "Usage: $0 <operator_address> <ip_address> [description]"
    echo ""
    echo "Example:"
    echo "  $0 0x1234...5678 192.168.1.100 \"Office network\""
    exit 1
fi

OPERATOR_ADDRESS="$1"
IP_ADDRESS="$2"
DESCRIPTION="${3:-Added via script}"

# Load database config
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-explorer}"
DB_PASSWORD="${DB_PASSWORD:-changeme}"
DB_NAME="${DB_NAME:-explorer}"

export PGPASSWORD="$DB_PASSWORD"

echo "Adding IP to whitelist:"
echo "  Operator: $OPERATOR_ADDRESS"
echo "  IP: $IP_ADDRESS"
echo "  Description: $DESCRIPTION"
echo ""

QUERY="
INSERT INTO operator_ip_whitelist (operator_address, ip_address, description)
VALUES (\$1, \$2, \$3)
ON CONFLICT (operator_address, ip_address) DO UPDATE SET
    description = EXCLUDED.description;
"

if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" \
    -c "$QUERY" \
    -v operator_address="$OPERATOR_ADDRESS" \
    -v ip_address="$IP_ADDRESS" \
    -v description="$DESCRIPTION"; then
    echo "✅ IP address added to whitelist"
else
    echo "❌ Failed to add IP address"
    exit 1
fi

unset PGPASSWORD

