#!/bin/bash

# Ansible Vault Setup Script
set -e

VAULT_PASSWORD_FILE="$HOME/.ansible_vault_pass"
VAULT_FILE="group_vars/orangepi_vault.yml"

echo "🔐 Ansible Vault Setup for OrangePi"
echo "=================================="

# Check if vault password file exists
if [[ -f "$VAULT_PASSWORD_FILE" ]]; then
    echo "✅ Vault password file already exists at $VAULT_PASSWORD_FILE"
else
    echo "📝 Creating vault password file..."
    echo "Please enter your vault password (this will be saved to $VAULT_PASSWORD_FILE):"
    read -s vault_password
    echo "$vault_password" > "$VAULT_PASSWORD_FILE"
    chmod 600 "$VAULT_PASSWORD_FILE"
    echo "✅ Vault password file created and secured"
fi

# Test vault access
echo "🧪 Testing vault access..."
if ansible-vault view "$VAULT_FILE" --vault-password-file "$VAULT_PASSWORD_FILE" > /dev/null 2>&1; then
    echo "✅ Vault access confirmed"
else
    echo "❌ Cannot access vault. Please check your password."
    echo "You can edit the vault with: ansible-vault edit $VAULT_FILE"
    exit 1
fi

echo ""
echo "🎉 Setup complete! You can now use:"
echo "  ./deploy-ansible.sh --help              # Show usage"
echo "  ./deploy-ansible.sh                     # Deploy all services"
echo "  ./deploy-ansible.sh immich duplicati    # Deploy specific services"
echo "  ./deploy-ansible.sh --list              # Show available services"
echo ""
echo "To edit secrets: ansible-vault edit $VAULT_FILE"