#!/bin/bash
# Refresh Vault and Grist tokens
# Tokens are written to files only, never exposed in stdout

TOKEN_DIR="/home/jcbeasley/.openclaw/workspace/.tokens"
VAULT_URL="https://beavault.beawit.net:8200"

mkdir -p "$TOKEN_DIR"

# Step 1: Authenticate to Vault
curl -sk -X POST \
  -d '{"role_id":"75d2dcfb-9c65-7f60-59b4-eee8c7f8dc0e","secret_id":"6202b465-2f25-547c-ec07-f47cfc4dda3e"}' \
  "$VAULT_URL/v1/auth/approle/login" \
  > "$TOKEN_DIR/vault_auth_response.json"

# Step 2: Extract Vault token
python3 -c "
import json
with open('$TOKEN_DIR/vault_auth_response.json') as f:
    data = json.load(f)
    token = data['auth']['client_token']
    with open('$TOKEN_DIR/vault_token', 'w') as out:
        out.write(token)
"

# Step 3: Get Grist token from Vault (direct file reference, no variable assignment)
curl -sk -H "X-Vault-Token: $(cat $TOKEN_DIR/vault_token)" \
  "$VAULT_URL/v1/kv/data/api/integration/grist" \
  > "$TOKEN_DIR/grist_vault_response.json"

# Step 4: Extract Grist token
python3 -c "
import json
with open('$TOKEN_DIR/grist_vault_response.json') as f:
    data = json.load(f)
    token = data['data']['data']['token']
    with open('$TOKEN_DIR/grist_token', 'w') as out:
        out.write(token)
"

# Step 5: Clean up
rm -f "$TOKEN_DIR/vault_auth_response.json" "$TOKEN_DIR/grist_vault_response.json"

echo "Tokens refreshed successfully"