#!/bin/bash

echo "=== MultiPortal Manual Cleanup & Install Script ==="

# Step 1: Prompt for FQDN
read -p "Enter your desired FQDN (e.g. multiportal.domain.local): " MYFQDN
if [ -z "$MYFQDN" ]; then
    echo "❌ No FQDN entered. Exiting."
    exit 1
fi

WEB_DIR="/var/www/$MYFQDN"

# Step 2: Test URL availability
echo -e "\n[Step 2] Checking access to version.txt..."
if wget --spider -q https://downloads.multiportal.io/latest/version.txt; then
    echo "✅ Access to version.txt confirmed."
else
    echo "❌ Unable to access version.txt. Please check your internet/DNS settings."
fi

if command -v mariadb >/dev/null 2>&1; then
    DB_CLI="mariadb"
elif command -v mysql >/dev/null 2>&1; then
    DB_CLI="mysql"
fi
# Step 3: Drop MySQL user and database
echo -e "\n[Step 3] Removing MySQL user and database 'multiportal'..."
sudo $DB_CLI -e "DROP USER IF EXISTS 'multiportal'@'localhost'; DROP DATABASE IF EXISTS multiportal;"
echo "✅ MySQL user and database removed."

# Step 4: Confirm and delete existing directory
echo -e "\n[Step 4] Preparing to remove directory: $WEB_DIR"
if [ -d "$WEB_DIR" ]; then
    read -p "❗ Are you sure you want to delete $WEB_DIR? [y/N]: " confirm
    if [[ "$confirm" =~ ^[Yy]$ ]]; then
        sudo rm -rf "$WEB_DIR"
        echo "✅ Directory removed."
    else
        echo "❌ Aborted directory removal."
        exit 1
    fi
else
    echo "ℹ️ Directory $WEB_DIR does not exist, skipping removal."
fi

# Step 5: Download latest installer
echo -e "\n[Step 5] Downloading the latest installer..."
curl -o ./installMultiportal https://downloads.multiportal.io/installer/mpInstallation
chmod +x ./installMultiportal
echo "✅ Installer downloaded and made executable."

# Step 6: Run the installer
echo -e "\n[Step 6] Running installer for $MYFQDN..."
export MYFQDN
sudo php ./installMultiportal "$MYFQDN" 1.0.12
echo "✅ Installer executed."

# Step 7: Post-install message
echo -e "\n[Step 7] Installation complete. Please continue setup here:"
echo "➡️ https://wiki.multiportal.io/en/install/MultiPortal-Installation-Guide#setup-node-for-websockets"

