#!/bin/bash
# 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 Alpha V2 Release!"
echo "Alpha-Version 0.5.0"
echo "---------------------------------------------"
echo "This is a pre-release version. Due to the experimental nature of the Alpha V2 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."
echo ""
echo "This application will copy the previous instance to the /tmp folder and will need to be manually removed upon confirmation."
echo ""


# Define the source and destination directories
SOURCE_DIR=$(pwd)'/multiportal/'


# Check if the source directory exists
if [ -d "$SOURCE_DIR" ]; then
    echo "Source directory exists. Proceeding..."
else
    echo "Source directory does not exist. Exiting..."
    exit 1
fi

# Prompt for hostname
read -p "What is the hostname you're going to use?: " HOST_NAME

FORMATTED_DATE=$(date +"%Y-%m-%d_%H-%M-%S")
echo "Formatted date: $formatted_date"

WEB_DIR="/var/www/$HOST_NAME"
BACKUP_DIR="/tmp/backup_${HOST_NAME}_${FORMATTED_DATE}"

# Check if the source directory exists
if [ -d "$WEB_DIR" ]; then
    # Stop the multiportal service as it will freak out
    systemctl stop multiportal.service
    echo "Web directory exists. Proceeding..."
    echo "Backing up existing web directory to $BACKUP_DIR"
    echo "You can delete this after succesfully confirming your installation works. Otherwise it will delete after reboot."
    mv "$WEB_DIR" "$BACKUP_DIR"
else
    echo "Web directory does not exist. Exiting..."
    exit 1
fi

pm2 save
pm2 save --force
pm2 save
pm2 save --force
# List pm2 processes
echo "Listing PM2 processes"
pm2 list

# Stop and delete all pm2 processes
echo "Stopping and deleting all PM2 processes"
pm2 delete all

# Verify that all processes are stopped
echo "Verifying PM2 processes"
pm2 list

# Copy the new files to the web directory
echo "Copying new files to the web directory..."
mv "$SOURCE_DIR/" "$WEB_DIR"

# Restore the .env file from the backup, if it exists
echo "Restoring required files from backup..."
if [ -f "$BACKUP_DIR/.env" ]; then
    cp "$BACKUP_DIR/.env" "$WEB_DIR/"
fi

# Restore the websockets directory contents from the backup, if it exists
# if [ -d "$BACKUP_DIR/websockets" ]; then
#     cp -r "$BACKUP_DIR/websockets/." "$WEB_DIR/websockets/"
#     if [ -f "$WEB_DIR/websockets/old.js" ]; then
#         rm "$WEB_DIR/websockets/old.js"
#     fi
# fi
# Restore the vendor directory from the backup, if it exists
if [ -d "$BACKUP_DIR/vendor" ]; then
    cp -r "$BACKUP_DIR/vendor/" "$WEB_DIR/"
fi
echo "Required files from backup completed..."

# Function to set up the Yii framework
setup_yii() {
    chown www-data:www-data -R "$WEB_DIR"
    chmod 775 -R "$WEB_DIR"
    cd "$WEB_DIR" || exit 1

    # Make sure the 'init' file is executable
    chmod +x init

    ./init --env=Production --overwrite=y > /dev/null 2>&1

    # Check if Yii framework's 'yii' file is executable
    if [ ! -f "./yii" ]; then
        echo "The Yii 'yii' file does not exist in the expected location."
        systemctl start multiportal.service
        exit 1
    fi

    chmod +x ./yii

    # Run Yii migration
    ./yii migrate --interactive=0 > /dev/null 2>&1
    ./yii server/update-routes >/dev/null 2>&1
    ./yii generate-api-key false >/dev/null 2>&1
    chown www-data:www-data -R "$WEB_DIR"
    chmod 775 -R "$WEB_DIR"

}

run_composer(){
    echo "Running Composer... " 

    cd "$WEB_DIR"

    # Run composer update after removing existing lock and vendor
    composer update --no-interaction > composer-update.log  >/dev/null 2>&1
    
    if [ $? -ne 0 ]; then
        echo "Composer update failed. Check composer-update.log for details."
        systemctl start multiportal.service
        exit 1
    fi

    # Set permissions after composer update
    chown www-data:www-data -R "$WEB_DIR"
    chmod 775 -R "$WEB_DIR"
    
    echo "Composer completed successfully."
}

setup_node(){
    cd "$WEB_DIR/websockets"
    sudo npm install >/dev/null 2>&1
}
#Run composer update
run_composer
setup_node
# Run the setup_yii function
setup_yii


# Stop the multiportal service as it will freak out
systemctl start multiportal.service

echo "Setup has been completed"
echo "Please navigate to your website to confirm the installation works."
echo "Once confirmed, you can delete the backup directory at $BACKUP_DIR otherwise it will delete after your next reboot"
echo ""
