#!/bin/bash
set -e

# Initialize Ansible Secrets
# This script helps set up the Ansible vault file for the first time

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ANSIBLE_DIR="$(dirname "$SCRIPT_DIR")"
SECRETS_DIR="$ANSIBLE_DIR/secrets"

echo "🔐 Ansible Secrets Initialization"
echo "=================================="
echo ""

# Check if running from correct directory
if [ ! -f "$ANSIBLE_DIR/ansible.cfg" ]; then
    echo "❌ Error: Must run from deployment/ansible directory"
    exit 1
fi

# Step 1: Create vault password file
echo "Step 1: Vault Password"
echo "----------------------"

if [ -f "$SECRETS_DIR/.vault_pass" ]; then
    echo "⚠️  Vault password file already exists: $SECRETS_DIR/.vault_pass"
    read -p "Do you want to replace it? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Keeping existing vault password file."
    else
        rm "$SECRETS_DIR/.vault_pass"
        read -sp "Enter new vault password: " VAULT_PASS
        echo
        read -sp "Confirm vault password: " VAULT_PASS_CONFIRM
        echo

        if [ "$VAULT_PASS" != "$VAULT_PASS_CONFIRM" ]; then
            echo "❌ Passwords don't match!"
            exit 1
        fi

        echo "$VAULT_PASS" > "$SECRETS_DIR/.vault_pass"
        chmod 600 "$SECRETS_DIR/.vault_pass"
        echo "✅ Vault password file created"
    fi
else
    read -sp "Enter vault password: " VAULT_PASS
    echo
    read -sp "Confirm vault password: " VAULT_PASS_CONFIRM
    echo

    if [ "$VAULT_PASS" != "$VAULT_PASS_CONFIRM" ]; then
        echo "❌ Passwords don't match!"
        exit 1
    fi

    echo "$VAULT_PASS" > "$SECRETS_DIR/.vault_pass"
    chmod 600 "$SECRETS_DIR/.vault_pass"
    echo "✅ Vault password file created"
fi

echo ""

# Step 2: Create production vault file
echo "Step 2: Production Vault File"
echo "-----------------------------"

if [ -f "$SECRETS_DIR/production.vault.yml" ]; then
    echo "⚠️  Production vault file already exists"
    read -p "Do you want to decrypt and edit it? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        ansible-vault edit "$SECRETS_DIR/production.vault.yml" \
            --vault-password-file "$SECRETS_DIR/.vault_pass"
        echo "✅ Vault file updated"
    fi
else
    echo "Creating new vault file from example..."
    cp "$SECRETS_DIR/production.vault.yml.example" "$SECRETS_DIR/production.vault.yml"

    echo ""
    echo "⚠️  IMPORTANT: You must edit the vault file and replace all 'change-me' values!"
    echo ""
    read -p "Press ENTER to edit the vault file now..."

    ${EDITOR:-nano} "$SECRETS_DIR/production.vault.yml"

    echo ""
    echo "Encrypting vault file..."
    ansible-vault encrypt "$SECRETS_DIR/production.vault.yml" \
        --vault-password-file "$SECRETS_DIR/.vault_pass"

    echo "✅ Production vault file created and encrypted"
fi

echo ""

# Step 3: Verify vault file
echo "Step 3: Verification"
echo "-------------------"

echo "Testing vault decryption..."
if ansible-vault view "$SECRETS_DIR/production.vault.yml" \
    --vault-password-file "$SECRETS_DIR/.vault_pass" > /dev/null 2>&1; then
    echo "✅ Vault file can be decrypted successfully"
else
    echo "❌ Failed to decrypt vault file!"
    exit 1
fi

# Check for example values
echo "Checking for unchanged example values..."
EXAMPLE_VALUES=$(ansible-vault view "$SECRETS_DIR/production.vault.yml" \
    --vault-password-file "$SECRETS_DIR/.vault_pass" | grep -c "change-me" || true)

if [ "$EXAMPLE_VALUES" -gt 0 ]; then
    echo "⚠️  WARNING: Found $EXAMPLE_VALUES 'change-me' placeholder values!"
    echo "   You must replace these before deploying to production."
    echo ""
    read -p "Do you want to edit the vault file now? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        ansible-vault edit "$SECRETS_DIR/production.vault.yml" \
            --vault-password-file "$SECRETS_DIR/.vault_pass"
    fi
else
    echo "✅ No placeholder values found"
fi

echo ""

# Step 4: Setup SSH key
echo "Step 4: SSH Key Setup"
echo "--------------------"

SSH_KEY="$HOME/.ssh/production"

if [ -f "$SSH_KEY" ]; then
    echo "✅ SSH key already exists: $SSH_KEY"
else
    echo "SSH key not found. Creating new key..."
    ssh-keygen -t ed25519 -f "$SSH_KEY" -C "ansible-deploy" -N ""
    chmod 600 "$SSH_KEY"
    chmod 644 "$SSH_KEY.pub"
    echo "✅ SSH key created"
    echo ""
    echo "📋 Public key:"
    cat "$SSH_KEY.pub"
    echo ""
    echo "⚠️  You must add this public key to the production server:"
    echo "   ssh-copy-id -i $SSH_KEY.pub deploy@94.16.110.151"
    echo ""
    read -p "Press ENTER to continue..."
fi

echo ""

# Step 5: Test connection
echo "Step 5: Connection Test"
echo "----------------------"

read -p "Do you want to test the connection to production? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Testing Ansible connection..."
    if ansible production -m ping 2>&1 | grep -q "SUCCESS"; then
        echo "✅ Connection successful!"
    else
        echo "❌ Connection failed!"
        echo ""
        echo "Troubleshooting steps:"
        echo "1. Verify SSH key is added to server: ssh-copy-id -i $SSH_KEY.pub deploy@94.16.110.151"
        echo "2. Test SSH manually: ssh -i $SSH_KEY deploy@94.16.110.151"
        echo "3. Check inventory file: cat $ANSIBLE_DIR/inventory/production.yml"
    fi
fi

echo ""
echo "✅ Setup complete!"
echo ""
echo "Next steps:"
echo "1. Review vault file: ansible-vault view secrets/production.vault.yml --vault-password-file secrets/.vault_pass"
echo "2. Deploy secrets: ansible-playbook playbooks/setup-production-secrets.yml --vault-password-file secrets/.vault_pass"
echo "3. Deploy application: See README.md for deployment instructions"
echo ""
echo "📖 For more information, see: deployment/ansible/README.md"
