#!/bin/bash
#
# Fix MariaDB setup after initial installation
#

set -e

echo "=========================================="
echo "Fixing MariaDB Setup"
echo "=========================================="
echo ""

# Secure installation using sudo mysql (unix_socket auth)
echo "[1/4] Securing MariaDB installation..."
sudo mysql <<'EOF'
ALTER USER 'root'@'localhost' IDENTIFIED BY 'CT_rmm_root_2026';
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;
EOF
echo "[OK] MariaDB secured"
echo ""

# Create ClaudeTools database
echo "[2/4] Creating ClaudeTools database..."
sudo mysql -u root -pCT_rmm_root_2026 <<'EOF'
CREATE DATABASE IF NOT EXISTS claudetools CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE USER IF NOT EXISTS 'claudetools'@'172.16.3.%' IDENTIFIED BY 'CT_e8fcd5a3952030a79ed6debae6c954ed';
GRANT ALL PRIVILEGES ON claudetools.* TO 'claudetools'@'172.16.3.%';

CREATE USER IF NOT EXISTS 'claudetools'@'localhost' IDENTIFIED BY 'CT_e8fcd5a3952030a79ed6debae6c954ed';
GRANT ALL PRIVILEGES ON claudetools.* TO 'claudetools'@'localhost';

FLUSH PRIVILEGES;
EOF
echo "[OK] Database and users created"
echo ""

# Configure for network access
echo "[3/4] Configuring MariaDB for network access..."
sudo sed -i 's/bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/' /etc/mysql/mariadb.conf.d/50-server.cnf
sudo systemctl restart mariadb
echo "[OK] Network access configured"
echo ""

# Test connection
echo "[4/4] Testing connection..."
mysql -h localhost -u claudetools -pCT_e8fcd5a3952030a79ed6debae6c954ed -e "SELECT 'Connection successful!' AS status, DATABASE() AS current_db;"
echo "[OK] Connection test passed"
echo ""

echo "=========================================="
echo "MariaDB Setup Complete!"
echo "=========================================="
echo ""
echo "Database: claudetools"
echo "User: claudetools"
echo "Password: CT_e8fcd5a3952030a79ed6debae6c954ed"
echo "Host: 172.16.3.30:3306"
echo ""
echo "Next: Test from Windows with:"
echo "  mysql -h 172.16.3.30 -u claudetools -pCT_e8fcd5a3952030a79ed6debae6c954ed claudetools"
echo ""
