#!/bin/bash

# URVault MANDATORY Fresh Install Script
# This script ALWAYS drops the database - no questions asked
# Use this for beta testing to ensure clean installations

set -e

echo "============================================================"
echo "URVault FRESH INSTALL (MANDATORY DATABASE DROP)"
echo "============================================================"
echo ""
echo "⚠️  WARNING: This will DELETE ALL existing URVault data!"
echo ""
read -p "Are you sure you want to continue? (yes/no): " confirm

if [ "$confirm" != "yes" ]; then
  echo "Installation cancelled."
  exit 1
fi

echo ""
echo "🗑️  Dropping existing database..."
echo ""

# Detect MySQL authentication method
MYSQL_CMD=""

# Try 1: sudo mysql (socket auth with sudo)
if sudo -n mysql -u root -e "SELECT 1;" 2>/dev/null; then
  echo "✓ Using sudo mysql (socket authentication)"
  MYSQL_CMD="sudo mysql -u root"
# Try 2: mysql without password (socket auth)
elif mysql -u root -e "SELECT 1;" 2>/dev/null; then
  echo "✓ Using mysql (socket authentication)"
  MYSQL_CMD="mysql -u root"
# Try 3: Password authentication
else
  echo "MySQL requires password authentication."
  echo "Enter MySQL root password:"
  read -s MYSQL_PASSWORD
  if mysql -u root -p"$MYSQL_PASSWORD" -e "SELECT 1;" 2>/dev/null; then
    echo "✓ Password accepted"
    MYSQL_CMD="mysql -u root -p$MYSQL_PASSWORD"
  else
    echo "❌ MySQL authentication failed"
    echo ""
    echo "Please drop the database manually:"
    echo "  sudo mysql -u root -e 'DROP DATABASE IF EXISTS urvault;'"
    echo "  sudo mysql -u root -e \"DROP USER IF EXISTS 'urvault'@'localhost';\""
    echo ""
    echo "Then run: npm run install-urvault"
    exit 1
  fi
fi

if [ -z "$MYSQL_CMD" ]; then
  echo "❌ Could not connect to MySQL"
  exit 1
fi

echo ""
echo "Dropping database and user..."
$MYSQL_CMD -e "DROP DATABASE IF EXISTS urvault;"
$MYSQL_CMD -e "DROP USER IF EXISTS 'urvault'@'localhost';" 2>/dev/null || true
echo "✅ Database and user dropped"

echo ""
echo "🗑️  Resetting setup state..."
STORAGE_PATH="${STORAGE_PATH:-$HOME/urvault-backups}"
CONFIG_FILE="$STORAGE_PATH/setup-config.json"
if [ -f "$CONFIG_FILE" ]; then
  echo '{"setupCompleted":false,"version":"1.0.0","adminConfigured":false,"storageConfigured":false,"databaseConfigured":false}' > "$CONFIG_FILE"
  echo "✅ Setup config reset: $CONFIG_FILE"
fi

echo ""
echo "📦 Running auto-installer..."
node install/auto-installer.js

echo ""
echo "✅ Fresh installation complete!"
echo ""
echo "Start the server with: ./start-server.sh"
echo "Then open the URL shown at the end of the installer output."
