#!/bin/bash
#
# ClaudeTools - Install MariaDB on RMM Server
# Run this on 172.16.3.30 as guru user
#

set -e

echo "=========================================="
echo "Installing MariaDB on RMM Server"
echo "=========================================="
echo ""

# Install MariaDB
echo "[1/7] Installing MariaDB..."
sudo apt update
sudo apt install -y mariadb-server mariadb-client
echo "[OK] MariaDB installed"
echo ""

# Start and enable service
echo "[2/7] Starting MariaDB service..."
sudo systemctl start mariadb
sudo systemctl enable mariadb
echo "[OK] MariaDB service started and enabled"
echo ""

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

# Create ClaudeTools database
echo "[4/7] 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 "[5/7] 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
echo "[OK] Network access configured"
echo ""

# Restart MariaDB
echo "[6/7] Restarting MariaDB..."
sudo systemctl restart mariadb
echo "[OK] MariaDB restarted"
echo ""

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

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