#!/bin/bash
export COMPOSER_ALLOW_SUPERUSER=1;
# Ensure the script is run as root
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

# Welcome to Multiportal

echo "---------------------------------------------"
echo "Welcome to MultiPortal Beta Release!"
echo "---------------------------------------------"
echo "This is a beta version. Due to the experimental nature of the Beta release"
echo "You may experience bugs, instability, or incomplete features. Use with caution and report any issues you encounter."
echo ""
echo "This Script will update your MultiPortal application to the latest version"
echo ""
echo "---------------------------------------------"

# Check if the directory exists
installationDirectory=$(pwd)
# Set the CaddyServer version and architecture
REPO_URL="https://downloads.multiportal.io/installer/mpUpdate"
PHPVERSION=8.2
# Main Script Execution
HOST_NAME=$1
# Check if the hostname is valid
if [ -z "$HOST_NAME" ]; then
    read -p "What is the FQDN you have used for your MultiPortal instance: " HOST_NAME < /dev/tty
fi
if [ -z "$HOST_NAME" ]; then
    echo "Hostname cannot be empty. Exiting..."
    exit 1
fi
WEB_DIR="/var/www/$HOST_NAME"

if [ ! -d "/var/www/$HOST_NAME" ]; then
    echo "Directory does not exist. Exiting..."
    exit 1
fi
DEST_FILE="$installationDirectory/updateMultiportalRepo"

get_installer() {
    # Download the install repo file
    echo "Downloading the MultiPortal update file..."
    curl -o "$DEST_FILE" "$REPO_URL" >/dev/null 2>&1

    # Check if the file was downloaded successfully
    if [ $? -eq 0 ] && [ -f "$DEST_FILE" ]; then
        chmod +x "$DEST_FILE"
        echo "File downloaded successfully."
    else
        echo "Failed to download the installer. Exiting..."
        exit 1
    fi
}

update_multiportal() {
    # Check if the installer file exists before executing it
    if [ -f "$DEST_FILE" ]; then
        php "$DEST_FILE" "$HOST_NAME"
    else
        echo "Installer file not found. Exiting..."
        exit 1
    fi
    unlink "$installationDirectory/updateMultiportalRepo"   
}


setup_node() {
  # Set the PM2 directory path
    PM2_DIR="/var/www/.pm2"

    # Check if the directory exists
    if [ ! -d "$PM2_DIR" ]; then
        echo "Creating directory for PM2 at $PM2_DIR"
        
        # Create the directory with permissions
        mkdir -p "$PM2_DIR"
        chmod 0775 "$PM2_DIR"

        # Set ownership to www-data user and group
        chown www-data:www-data "$PM2_DIR"

        echo "PM2 directory created successfully with permissions and ownership set."
    else
        echo "PM2 directory already exists at $PM2_DIR"
    fi
    echo "Setting up Node... " 
    cd "$WEB_DIR/websockets"
    sudo npm install >/dev/null 2>&1
}

stop_pm2(){
    pm2 save >/dev/null 2>&1
    pm2 save --force >/dev/null 2>&1
    pm2 save >/dev/null 2>&1
    pm2 save --force >/dev/null 2>&1
    pm2 list >/dev/null 2>&1

    # Stop and delete all pm2 processes
    echo "Stopping and deleting and clearing Console processes"
    pm2 delete all >/dev/null 2>&1

    # Verify that all processes are stopped
    echo "Verifying Console"
    pm2 list >/dev/null 2>&1
}

update_php() {
    echo "Checking if PHP $PHPVERSION is installed..."
    if command -v php$PHPVERSION &> /dev/null; then
        PHP_CONFIG_FILE="/etc/php/$PHPVERSION/fpm/php.ini"
        echo "Updating PHP configuration file $PHP_CONFIG_FILE..."
        if [ -f "$PHP_CONFIG_FILE" ]; then
            # Adjust upload related settings
            sed -i "s/^;*upload_max_filesize = .*/upload_max_filesize = 10G/" "$PHP_CONFIG_FILE"
            sed -i "s/^;*post_max_size = .*/post_max_size = 10G/" "$PHP_CONFIG_FILE"
            sed -i "s/^;*max_execution_time = .*/max_execution_time = 360/" "$PHP_CONFIG_FILE"
            sed -i "s/^;*max_file_uploads = .*/max_file_uploads = 999/" "$PHP_CONFIG_FILE"
            echo "PHP configuration updated successfully."
        else
            echo "Warning: PHP configuration file not found at $PHP_CONFIG_FILE. Upload related settings were not updated."
        fi
    fi
    systemctl restart php$PHPVERSION-fpm >/dev/null 2>&1
    echo "PHP-FPM service restarted successfully."
}
get_installer

systemctl stop multiportal.service
update_php
stop_pm2
update_multiportal
setup_node

systemctl start multiportal.service
wait $!

echo "---------------------------------------"
echo "Update has completed"
echo "---------------------------------------"
echo "To view your instance, visit https://$HOST_NAME"
echo "The directory of your instance is $WEB_DIR"
echo "---------------------------------------"
