#!/usr/bin/env bash
# Generate aperture configuration from template.
#
# Usage:
#   setup.sh                                    # Defaults (mainnet, lnd)
#   setup.sh --network testnet --insecure       # Testnet, no TLS
#   setup.sh --no-auth                          # Disable L402 auth
#   setup.sh --port 8081                        # Custom listen port

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APERTURE_DIR="$HOME/.aperture"
CONFIG_FILE="$APERTURE_DIR/aperture.yaml"
NETWORK="mainnet"
PORT="8081"
INSECURE=false
NO_AUTH=false
LND_HOST="localhost:10009"
LND_TLS="$HOME/.lnd/tls.cert"
LND_MACDIR=""
SERVICE_PORT="8080"
SERVICE_PRICE="100"

# Parse arguments.
while [[ $# -gt 0 ]]; do
    case $1 in
        --network)
            NETWORK="$2"
            shift 2
            ;;
        --port)
            PORT="$2"
            shift 2
            ;;
        --insecure)
            INSECURE=true
            shift
            ;;
        --no-auth)
            NO_AUTH=true
            shift
            ;;
        --lnd-host)
            LND_HOST="$2"
            shift 2
            ;;
        --lnd-tls)
            LND_TLS="$2"
            shift 2
            ;;
        --lnd-macdir)
            LND_MACDIR="$2"
            shift 2
            ;;
        --service-port)
            SERVICE_PORT="$2"
            shift 2
            ;;
        --service-price)
            SERVICE_PRICE="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: setup.sh [options]"
            echo ""
            echo "Generate aperture configuration."
            echo ""
            echo "Options:"
            echo "  --network NETWORK        Bitcoin network (default: mainnet)"
            echo "  --port PORT              Listen port (default: 8081)"
            echo "  --insecure               Disable TLS"
            echo "  --no-auth                Disable L402 authentication"
            echo "  --lnd-host HOST          lnd gRPC host (default: localhost:10009)"
            echo "  --lnd-tls PATH           lnd TLS cert path"
            echo "  --lnd-macdir PATH        lnd macaroon directory"
            echo "  --service-port PORT      Backend service port (default: 8080)"
            echo "  --service-price SATS     Price per request in sats (default: 100)"
            exit 0
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    esac
done

# Auto-detect lnd macaroon directory if not specified.
if [ -z "$LND_MACDIR" ]; then
    LND_MACDIR="$HOME/.lnd/data/chain/bitcoin/$NETWORK"
fi

echo "=== Aperture Configuration Setup ==="
echo ""
echo "Network:      $NETWORK"
echo "Listen port:  $PORT"
echo "Insecure:     $INSECURE"
echo "Auth:         $([ "$NO_AUTH" = true ] && echo "disabled" || echo "enabled")"
echo "LND host:     $LND_HOST"
echo "Config:       $CONFIG_FILE"
echo ""

# Create aperture directory.
mkdir -p "$APERTURE_DIR"

# Build config.
cat > "$CONFIG_FILE" << YAML
# Aperture configuration generated by setup.sh
# Edit as needed: ~/.aperture/aperture.yaml

listenaddr: "localhost:$PORT"
debuglevel: "info"
dbbackend: "sqlite"

sqlite:
  dbfile: "$APERTURE_DIR/aperture.db"

insecure: $INSECURE

authenticator:
YAML

if [ "$NO_AUTH" = true ]; then
    cat >> "$CONFIG_FILE" << YAML
  disable: true
YAML
else
    cat >> "$CONFIG_FILE" << YAML
  network: "$NETWORK"
  lndhost: "$LND_HOST"
  tlspath: "$LND_TLS"
  macdir: "$LND_MACDIR"
YAML
fi

cat >> "$CONFIG_FILE" << YAML

services:
  - name: "default-api"
    hostregexp: ".*"
    pathregexp: '^/api/.*$'
    address: "127.0.0.1:$SERVICE_PORT"
    protocol: http
    price: $SERVICE_PRICE
    timeout: 31557600
    authwhitelistpaths:
      - '^/health$'
YAML

echo "Config written to $CONFIG_FILE"
echo ""

# Warn if invoice.macaroon is missing (required for aperture to create invoices).
if [ "$NO_AUTH" != true ]; then
    INVOICE_MACAROON="$LND_MACDIR/invoice.macaroon"
    if [ ! -f "$INVOICE_MACAROON" ]; then
        echo "WARNING: invoice.macaroon not found at $INVOICE_MACAROON"
        echo ""
        echo "Aperture requires invoice.macaroon in the macdir to create invoices."
        echo "Without it, aperture will fail to generate L402 challenges."
        echo ""

        BAKERY_SCRIPT="$SCRIPT_DIR/../../macaroon-bakery/scripts/bake.sh"
        if [ -x "$BAKERY_SCRIPT" ]; then
            echo "To bake one automatically:"
            echo "  $BAKERY_SCRIPT --role invoice-only --save-to $INVOICE_MACAROON"
        else
            echo "To create one, use the macaroon-bakery skill:"
            echo "  skills/macaroon-bakery/scripts/bake.sh --role invoice-only --save-to $INVOICE_MACAROON"
        fi
        echo ""
    fi
fi

echo "Next steps:"
echo "  1. Start a backend on port $SERVICE_PORT"
echo "  2. Start aperture: skills/aperture/scripts/start.sh"
echo "  3. Test: lnget -k https://localhost:$PORT/api/test"
