#!/bin/bash
# Script to extract CI_TOKEN (vault_git_token) from Ansible Vault
# Usage: ./scripts/get-ci-token-from-vault.sh

set -e

VAULT_FILE="deployment/ansible/secrets/production.vault.yml"
VAULT_PASS_FILE="deployment/ansible/.vault_pass"

# Check if vault file exists
if [ ! -f "$VAULT_FILE" ]; then
    echo "Error: Vault file not found at $VAULT_FILE"
    exit 1
fi

# Try to extract token
if [ -f "$VAULT_PASS_FILE" ]; then
    # Use vault password file
    TOKEN=$(ansible-vault view "$VAULT_FILE" --vault-password-file "$VAULT_PASS_FILE" 2>/dev/null | grep "vault_git_token:" | cut -d'"' -f2 || echo "")
elif command -v ansible-playbook >/dev/null 2>&1; then
    # Try with ansible-playbook
    TOKEN=$(cd deployment/ansible && ansible-playbook -i localhost, -c local /dev/stdin --vault-password-file .vault_pass 2>/dev/null <<EOF || echo ""
---
- hosts: localhost
  gather_facts: no
  vars_files:
    - secrets/production.vault.yml
  tasks:
    - debug:
        var: vault_git_token
EOF
)
    TOKEN=$(echo "$TOKEN" | grep -oP "vault_git_token.*:\s*\K[^\s]+" || echo "")
else
    echo "Error: Cannot extract token. Please provide vault password manually or set GITEA_TOKEN directly."
    exit 1
fi

if [ -n "$TOKEN" ] && [ "$TOKEN" != "null" ] && [ "$TOKEN" != "undefined" ]; then
    echo "$TOKEN"
else
    echo "Error: Could not extract token from vault"
    exit 1
fi
