#!/bin/bash

# Enhance restoration script
# Version 1.1 powered by JoneSolutions.Com

# Set default IP
DEFAULT_IP="9.9.9.9"

# Function to display usage
usage() {
    echo "Usage: $0 [--ip <ip_address>]"
    echo "  --ip <ip_address>  Set the primary IP for SSO (default: $DEFAULT_IP)"
    exit 1
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        --ip)
            IP_ADDRESS=$2
            shift 2
            ;;
        --help)
            usage
            ;;
        *)
            echo "Unknown option: $1"
            usage
            ;;
    esac
done

# Set IP address
IP_ADDRESS=${IP_ADDRESS:-$DEFAULT_IP}

echo "Starting restoration process..."
echo "Using IP address: $IP_ADDRESS"
echo ""

# Stop services before beginning restoration
echo "0. Stopping services..."
systemctl stop orchd
systemctl stop appcd
echo "Services stopped successfully."
echo ""

# Step 1: Remove existing databases and create new ones
echo "1. Recreating databases..."
sudo -u postgres psql -c "DROP DATABASE IF EXISTS orchd;"
sudo -u postgres psql -c "DROP DATABASE IF EXISTS authd;"
sudo -u postgres psql -c "CREATE DATABASE orchd;"
sudo -u postgres psql -c "CREATE DATABASE authd;"
sudo -u postgres psql -d orchd -c "GRANT USAGE, CREATE ON SCHEMA public TO orchd;"
sudo -u postgres psql -d authd -c "GRANT USAGE, CREATE ON SCHEMA public TO orchd;"
echo "Database recreation completed."
echo ""

# Step 2: Import data
echo "2. Importing data..."
if [ -f "/var/orchd/orchd.sql" ]; then
    sudo -u orchd psql -d orchd < /var/orchd/orchd.sql
    echo "Imported orchd.sql successfully."
else
    echo "Error: /var/orchd/orchd.sql not found!"
    exit 1
fi

if [ -f "/var/orchd/authd.sql" ]; then
    sudo -u orchd psql -d authd < /var/orchd/authd.sql
    echo "Imported authd.sql successfully."
else
    echo "Error: /var/orchd/authd.sql not found!"
    exit 1
fi
echo "Data import completed."
echo ""

# Step 3: Start services
echo "3. Starting services..."
systemctl start orchd
systemctl start appcd
systemctl start filerd
echo "Services started."
echo ""

# Step 4: Recreate websites
echo "4. Recreating websites..."
WEBSITE_COUNT=$(sudo -u orchd psql -At -c "SELECT count(*) FROM websites WHERE kind = 1;")
echo "Found $WEBSITE_COUNT control panel websites to recreate."

sudo -u orchd psql -At -c "
SELECT 'appcd-cli create-website ' || w.id || ' ' || w.unix_user || ' ' || d.domain || ' php83 control-panel'
FROM websites w
JOIN domain_mappings dm ON w.id = dm.website_id
JOIN domains d ON dm.domain_id = d.id
WHERE w.kind = 1 and dm.kind = 'primary';
" | bash
echo "Website recreation completed."
echo ""

# Step 5: Update primary IP
echo "5. Updating primary IP to $IP_ADDRESS..."
sudo -u orchd psql -c "UPDATE servers SET primary_ip = '$IP_ADDRESS' where id = '00000000-0000-0000-0000-000000000000';"
sudo -u orchd psql -c "UPDATE server_ips SET ip = '$IP_ADDRESS' where server_id = '00000000-0000-0000-0000-000000000000';"
echo "Primary IP updated."
echo ""

# Step 6: Fix permissions
echo "6. Fixing file permissions..."
chown orchd:orchd /var/local/enhance/orchd/private/orchd.key /etc/ssl/certs/enhance/orchd.crt
chown -R orchd:orchd /var/www/control-panel/screenshots /var/www/control-panel/assets

# Check if Cloudflare key exists and fix permissions if it does
if [ -f "/var/local/enhance/orchd/cloudflare.key" ]; then
    chown orchd:orchd /var/local/enhance/orchd/cloudflare.key
    echo "Cloudflare key permissions fixed."
fi
echo "Permission fixes completed."
echo ""

# Final step: Regenerate proxies
echo "7. Regenerating control panel proxies..."
ecp regenerate-control-panel-proxies
echo "Proxy regeneration completed."
echo ""

# Completion message
echo "Restoration process completed successfully!"
echo ""
echo "================================================"
echo "                     SUMMARY"
echo "================================================"
echo "- Services stopped and restarted"
echo "- Databases recreated and data imported"
echo "- $WEBSITE_COUNT websites recreated"
echo "- Primary IP set to $IP_ADDRESS"
echo "- File permissions corrected"
echo "- Proxies regenerated"
echo ""
echo "IMPORTANT NEXT STEPS:"
echo "1. Update the DNS for your control panel domain to point to $IP_ADDRESS"
echo "2. Wait for your local DNS cache to update (this may take some time)"
echo "3. Your panel should be working normally once DNS propagates"
echo "================================================"

exit 0
