#!/usr/bin/env bash
#
# Setup encryption services for typedialog end-to-end testing
# Configures Age (local) and RustyVault (HTTP service)
#
# Usage: ./scripts/encryption-test-setup.sh
#

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== typedialog Encryption Services Setup ===${NC}\n"

# ============================================================================
# Age Setup (Local, No Service Required)
# ============================================================================

echo -e "${YELLOW}1. Setting up Age (local file-based encryption)...${NC}"

if ! command -v age &> /dev/null; then
  echo -e "${RED}   ✗ age not installed${NC}"
  echo "   Install with:"
  echo "     macOS: brew install age"
  echo "     Linux: sudo apt-get install age"
  exit 1
fi

mkdir -p ~/.age

if [ ! -f ~/.age/key.txt ]; then
  echo "   → Generating Age key pair..."
  age-keygen -o ~/.age/key.txt
fi

# Extract and create public key file (Age backend expects separate files)
if [ ! -f ~/.age/key.txt.pub ]; then
  echo "   → Creating public key file..."
  grep "public key:" ~/.age/key.txt | awk '{print $4}' > ~/.age/key.txt.pub
fi

export AGE_KEY_FILE="$HOME/.age/key.txt"
PUBLIC_KEY=$(cat ~/.age/key.txt.pub)

echo -e "${GREEN}   ✓ Age configured${NC}"
echo "   Key file: $AGE_KEY_FILE"
echo "   Public key: $PUBLIC_KEY"

# ============================================================================
# RustyVault Setup (HTTP Service, Docker-based)
# ============================================================================

echo ""
echo -e "${YELLOW}2. Setting up RustyVault (HTTP encryption service)...${NC}"

if ! command -v docker &> /dev/null; then
  echo -e "${YELLOW}   ⚠ Docker not found${NC}"
  echo "   RustyVault requires Docker. Install from: https://www.docker.com/"
  echo "   Skipping RustyVault setup (Age will be available for testing)"
  VAULT_AVAILABLE=false
else
  VAULT_AVAILABLE=true

  # Check if container already running
  if docker ps 2>/dev/null | grep -q rustyvault; then
    echo "   → RustyVault container already running"
  else
    echo "   → Starting RustyVault container..."

    # Try to run container
    if ! docker run -d \
      --name rustyvault \
      -p 8200:8200 \
      -e RUSTYVAULT_LOG_LEVEL=info \
      rustyvault:latest 2>/dev/null; then

      echo -e "${RED}   ✗ Failed to start RustyVault container${NC}"
      echo "   Possible causes:"
      echo "     1. Image not available: docker pull rustyvault:latest"
      echo "     2. Port 8200 already in use"
      echo "     3. Docker daemon not running"
      VAULT_AVAILABLE=false
    else
      sleep 3
      echo "   → Initializing RustyVault..."

      # Initialize vault
      INIT_RESPONSE=$(curl -s -X POST http://localhost:8200/v1/sys/init \
        -d '{"secret_shares": 1, "secret_threshold": 1}' 2>/dev/null || echo '{}')

      VAULT_KEY=$(echo "$INIT_RESPONSE" | jq -r '.keys[0] // empty' 2>/dev/null || echo '')

      if [ -z "$VAULT_KEY" ]; then
        echo -e "${RED}   ✗ Failed to initialize RustyVault${NC}"
        echo "   Check if service is running: curl http://localhost:8200/v1/sys/health"
        VAULT_AVAILABLE=false
      else
        # Unseal vault
        curl -s -X PUT http://localhost:8200/v1/sys/unseal \
          -d "{\"key\": \"$VAULT_KEY\"}" > /dev/null 2>&1 || true

        # Enable transit engine
        echo "   → Enabling Transit secrets engine..."
        curl -s -X POST http://localhost:8200/v1/sys/mounts/transit \
          -H "X-Vault-Token: root" \
          -d '{"type": "transit"}' > /dev/null 2>&1 || true

        # Create encryption key
        echo "   → Creating encryption key..."
        curl -s -X POST http://localhost:8200/v1/transit/keys/typedialog-key \
          -H "X-Vault-Token: root" \
          -d '{}' > /dev/null 2>&1 || true

        export VAULT_ADDR="http://localhost:8200"
        export VAULT_TOKEN="root"

        echo -e "${GREEN}   ✓ RustyVault configured${NC}"
        echo "   Service: http://localhost:8200"
        echo "   Token: root (development only)"
      fi
    fi
  fi
fi

# ============================================================================
# Summary
# ============================================================================

echo ""
echo -e "${GREEN}=== Setup Complete ===${NC}\n"

echo "Encryption services available:"
echo -e "  ${GREEN}✓ Age${NC} (local file-based)"
if [ "$VAULT_AVAILABLE" = true ]; then
  echo -e "  ${GREEN}✓ RustyVault${NC} (HTTP service at http://localhost:8200)"
else
  echo -e "  ${RED}✗ RustyVault${NC} (not available)"
fi

echo ""
echo "Quick test commands:"
echo ""
echo "1. Test redaction (no service required):"
echo "   typedialog form examples/password_form.toml --redact --format json"
echo ""
echo "2. Test Age encryption:"
echo "   typedialog form examples/password_form.toml \\"
echo "     --encrypt --backend age --key-file ~/.age/key.txt --format json"
echo ""

if [ "$VAULT_AVAILABLE" = true ]; then
  echo "3. Test RustyVault encryption:"
  echo "   typedialog form examples/password_form.toml \\"
  echo "     --encrypt --backend rustyvault \\"
  echo "     --vault-addr http://localhost:8200 \\"
  echo "     --vault-token root \\"
  echo "     --vault-key-path 'transit/keys/typedialog-key' \\"
  echo "     --format json"
  echo ""
fi

echo "Run all encryption tests:"
echo "  cargo test --test nickel_integration test_encryption -- --nocapture"
echo ""

# Export for use in calling shell
cat > /tmp/typedialog-env.sh <<EOF
export AGE_KEY_FILE="$HOME/.age/key.txt"
EOF

if [ "$VAULT_AVAILABLE" = true ]; then
  cat >> /tmp/typedialog-env.sh <<EOF
export VAULT_ADDR="http://localhost:8200"
export VAULT_TOKEN="root"
EOF
fi

echo "To use these environment variables in your shell:"
echo "  source /tmp/typedialog-env.sh"
