#!/bin/bash
# Docker Secrets Setup Script
# Auto-generated by @vmenon25/mcp-server-webauthn-client
#
# This script verifies that Docker secrets exist and provides guidance

set -euo pipefail

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

echo "🔐 Docker Secrets Setup"
echo "======================="

# Check if secrets directory exists
if [ ! -d "$SECRETS_DIR" ]; then
  echo "❌ Secrets directory not found: $SECRETS_DIR"
  exit 1
fi

# Check for required secret files
REQUIRED_SECRETS=("postgres_password" "redis_password" "jwt_master_key")
MISSING_SECRETS=()

for secret in "${REQUIRED_SECRETS[@]}"; do
  if [ ! -f "$SECRETS_DIR/$secret" ]; then
    MISSING_SECRETS+=("$secret")
  fi
done

if [ ${#MISSING_SECRETS[@]} -eq 0 ]; then
  echo "✅ All required secrets are present"
  echo ""
  echo "Secret files:"
  for secret in "${REQUIRED_SECRETS[@]}"; do
    echo "  - $secret"
  done
  echo ""
  echo "🚀 Ready to run: docker compose up -d"
else
  echo "❌ Missing secrets:"
  for secret in "${MISSING_SECRETS[@]}"; do
    echo "  - $secret"
  done
  echo ""
  echo "Secrets were supposed to be auto-generated by the MCP server."
  echo "To manually create secrets, generate random passwords:"
  echo ""
  echo "  openssl rand -base64 32 | cut -c1-32 > secrets/postgres_password"
  echo "  openssl rand -base64 32 | cut -c1-32 > secrets/redis_password"
  echo "  openssl rand -base64 32 | cut -c1-32 > secrets/jwt_master_key"
  exit 1
fi

# Security check: warn if secrets have excessive permissions
echo ""
echo "🔒 Security Check:"
for secret in "${REQUIRED_SECRETS[@]}"; do
  PERMS=$(stat -f "%OLp" "$SECRETS_DIR/$secret" 2>/dev/null || stat -c "%a" "$SECRETS_DIR/$secret" 2>/dev/null)
  if [ "$PERMS" != "600" ] && [ "$PERMS" != "400" ]; then
    echo "⚠️  Warning: $secret has permissions $PERMS (recommended: 600)"
    echo "   Fix with: chmod 600 $SECRETS_DIR/$secret"
  fi
done

echo ""
echo "📖 Secret Rotation:"
echo "   1. Generate new passwords (openssl rand -base64 32)"
echo "   2. Update secret files in $SECRETS_DIR"
echo "   3. Restart services: docker compose restart"
