#!/bin/bash
#
# Test script to demonstrate the MySQL root credential prompting
#

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[0;33m'
NC='\033[0m'

# Function to prompt for MySQL root credentials if not in .env
prompt_mysql_root_credentials() {
  if [ -z "$DB_ROOT_USERNAME" ]; then
    echo -e "${YELLOW}MySQL root credentials are needed to grant/revoke ALTER permission${NC}"
    read -p "MySQL root username [root]: " DB_ROOT_USERNAME
    DB_ROOT_USERNAME="${DB_ROOT_USERNAME:-root}"
  fi

  if [ -z "$DB_ROOT_PASSWORD" ]; then
    read -sp "MySQL root password: " DB_ROOT_PASSWORD
    echo ""
  fi
}

# Function to execute MySQL commands as root
mysql_root_exec() {
  local sql="$1"

  # Ensure we have root credentials
  if [ -z "$DB_ROOT_USERNAME" ]; then
    return 1
  fi

  # Execute with credentials
  if [ -n "$DB_ROOT_PASSWORD" ]; then
    mysql -u "$DB_ROOT_USERNAME" -p"$DB_ROOT_PASSWORD" -e "$sql" 2>/dev/null
  else
    mysql -u "$DB_ROOT_USERNAME" -e "$sql" 2>/dev/null
  fi
}

echo -e "${BLUE}=== Testing MySQL Root Credential Prompting ===${NC}"
echo ""

# Simulate deployment scenario where .env doesn't have root credentials
unset DB_ROOT_USERNAME
unset DB_ROOT_PASSWORD

# Prompt for credentials
prompt_mysql_root_credentials

echo ""
echo -e "${GREEN}Credentials collected:${NC}"
echo "  Username: $DB_ROOT_USERNAME"
echo "  Password: $(echo "$DB_ROOT_PASSWORD" | sed 's/./*/g')"

echo ""
echo -e "${BLUE}Testing MySQL connection...${NC}"
if mysql_root_exec "SELECT 'Connection successful!' AS status;"; then
  echo -e "${GREEN}✓ MySQL root connection successful${NC}"
else
  echo -e "${YELLOW}✗ MySQL root connection failed - check credentials${NC}"
fi

echo ""
echo -e "${BLUE}=== Test Complete ===${NC}"
