#!/bin/bash

# Debug script to test database connection and show parsed values

echo "=== Database Connection Debug ==="
echo ""

if [ ! -f .env ]; then
    echo "ERROR: .env file not found"
    exit 1
fi

# Parse values exactly as the test script does (with comment stripping)
DB_DATABASE=$(grep "^DB_DATABASE=" .env | cut -d '=' -f2 | sed 's/#.*//' | tr -d '"' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/\r$//')
DB_USERNAME=$(grep "^DB_USERNAME=" .env | cut -d '=' -f2 | sed 's/#.*//' | tr -d '"' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/\r$//')
DB_PASSWORD=$(grep "^DB_PASSWORD=" .env | cut -d '=' -f2- | sed 's/#.*//' | sed 's/^"//' | sed 's/"$//' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/\r$//')
DB_HOST=$(grep "^DB_HOST=" .env | cut -d '=' -f2 | sed 's/#.*//' | tr -d '"' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/\r$//')

if [ -z "$DB_HOST" ]; then
    DB_HOST="localhost"
fi

echo "Parsed values from .env:"
echo "  DB_DATABASE: [$DB_DATABASE]"
echo "  DB_USERNAME: [$DB_USERNAME]"
echo "  DB_PASSWORD length: ${#DB_PASSWORD} characters"
echo "  DB_PASSWORD first char: [${DB_PASSWORD:0:1}]"
echo "  DB_PASSWORD last char: [${DB_PASSWORD: -1}]"
echo "  DB_HOST: [$DB_HOST]"
echo ""

# Try different connection methods
echo "Test 1: Trying connection with MYSQL_PWD..."
if MYSQL_PWD="$DB_PASSWORD" mysql -h"$DB_HOST" -u"$DB_USERNAME" "$DB_DATABASE" -e "SELECT 1 AS test;" 2>/tmp/mysql_error.log; then
    echo "  ✓ SUCCESS with MYSQL_PWD"
else
    echo "  ✗ FAILED with MYSQL_PWD"
    echo "  Error output:"
    cat /tmp/mysql_error.log
fi
echo ""

echo "Test 2: Trying connection to localhost instead of $DB_HOST..."
if MYSQL_PWD="$DB_PASSWORD" mysql -hlocalhost -u"$DB_USERNAME" "$DB_DATABASE" -e "SELECT 1 AS test;" 2>/tmp/mysql_error2.log; then
    echo "  ✓ SUCCESS with localhost"
else
    echo "  ✗ FAILED with localhost"
    echo "  Error output:"
    cat /tmp/mysql_error2.log
fi
echo ""

echo "Test 3: Trying without specifying host (socket connection)..."
if MYSQL_PWD="$DB_PASSWORD" mysql -u"$DB_USERNAME" "$DB_DATABASE" -e "SELECT 1 AS test;" 2>/tmp/mysql_error3.log; then
    echo "  ✓ SUCCESS with socket connection"
else
    echo "  ✗ FAILED with socket connection"
    echo "  Error output:"
    cat /tmp/mysql_error3.log
fi
echo ""

echo "Test 4: Check MySQL is listening..."
echo "  MySQL processes:"
ps aux | grep mysql | grep -v grep
echo ""
echo "  MySQL network listeners:"
netstat -tlnp 2>/dev/null | grep mysql || ss -tlnp 2>/dev/null | grep mysql
echo ""

echo "Test 5: Check if mysql command works at all..."
if mysql --version >/dev/null 2>&1; then
    echo "  ✓ mysql command is available: $(mysql --version)"
else
    echo "  ✗ mysql command not found"
fi
echo ""

# Cleanup
rm -f /tmp/mysql_error.log /tmp/mysql_error2.log /tmp/mysql_error3.log

echo "=== Debug Complete ==="
