#!/bin/bash
current="overtones-frontend"

# Get the owner of the home directory where the script is located
DIR_OWNER=$(stat -c '%U' "$HOME")

# Execute the following commands as the directory owner
sudo -u "$DIR_OWNER" bash <<EOF

# Function to check if a command exists
command_exists () {
    command -v "\$1" >/dev/null 2>&1
}

# Ensure npm binaries are in the PATH
export NPM_GLOBAL_PREFIX="\$HOME/.npm-global"
mkdir -p "\$NPM_GLOBAL_PREFIX/bin"
mkdir -p "\$NPM_GLOBAL_PREFIX/lib/node_modules"
export PATH="\$NPM_GLOBAL_PREFIX/bin:\$PATH"

echo "Current PATH: \$PATH"

echo "Checking if pm2 is installed"
if ! command_exists pm2; then
    echo "pm2 is not installed. Installing pm2..."
    npm config set prefix "\$NPM_GLOBAL_PREFIX"
    npm install -g pm2 || { echo "Error: Failed to install pm2"; exit 1; }
    export PATH="\$NPM_GLOBAL_PREFIX/bin:\$PATH"
    echo "pm2 installed. Updated PATH: \$PATH"
else
    echo "pm2 is already installed"
fi

# Verify pm2 installation
if ! command_exists pm2; then
    echo "Error: pm2 is not available even after installation."
    echo "Contents of \$NPM_GLOBAL_PREFIX/bin:"
    ls -l "\$NPM_GLOBAL_PREFIX/bin"
    echo "Contents of \$NPM_GLOBAL_PREFIX/lib/node_modules:"
    ls -l "\$NPM_GLOBAL_PREFIX/lib/node_modules"
    exit 1
else
    echo "pm2 is installed and available"
fi

echo "Install npm packages"
npm install || { echo "Error: npm install failed"; exit 1; }

echo "Start build process"
npm run build || { echo "Error: npm run build failed"; exit 1; }

echo "Restart or start pm2 app"
if pm2 describe $current > /dev/null; then
    pm2 restart $current || { echo "Error: pm2 restart failed"; exit 1; }
else
    pm2 start -f --name=$current npm -- start || { echo "Error: pm2 start failed"; exit 1; }
fi

echo "Save pm2 state"
pm2 save || { echo "Error: pm2 save failed"; exit 1; }

EOF

exit 0