#!/bin/bash
# Script to load database password from secret file
# This ensures DB_PASSWORD and DB_ROOT_PASSWORD match SPRING_DATASOURCE_PASSWORD
# Usage: source ./load-db-password.sh

SECRET_FILE="/run/secrets/honey-config.properties"

if [ ! -f "$SECRET_FILE" ]; then
    echo "❌ Error: Secret file not found at $SECRET_FILE"
    echo "   Please create the secret file first (see deployment guide Step 3.3)"
    return 1 2>/dev/null || exit 1
fi

# Read SPRING_DATASOURCE_PASSWORD from secret file
DB_PASSWORD=$(grep "^SPRING_DATASOURCE_PASSWORD=" "$SECRET_FILE" | cut -d'=' -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

if [ -z "$DB_PASSWORD" ]; then
    echo "❌ Error: SPRING_DATASOURCE_PASSWORD not found in secret file"
    echo "   Please ensure the secret file contains: SPRING_DATASOURCE_PASSWORD=your_password"
    return 1 2>/dev/null || exit 1
fi

# Export both variables (MySQL uses both)
export DB_PASSWORD="$DB_PASSWORD"
export DB_ROOT_PASSWORD="$DB_PASSWORD"

# Optionally load PMA_ABSOLUTE_URI from secret file (for phpMyAdmin path protection)
PMA_ABSOLUTE_URI=$(grep "^PMA_ABSOLUTE_URI=" "$SECRET_FILE" | cut -d'=' -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/^"//;s/"$//' | sed "s/^'//;s/'$//")
if [ -n "$PMA_ABSOLUTE_URI" ]; then
    export PMA_ABSOLUTE_URI="$PMA_ABSOLUTE_URI"
    echo "✅ PMA_ABSOLUTE_URI loaded from secret file"
fi

echo "✅ Database password loaded from secret file"
echo "   DB_PASSWORD and DB_ROOT_PASSWORD are now set (matching SPRING_DATASOURCE_PASSWORD)"



