#!/bin/sh
echo "Running EllieBot"
root=$(pwd)

choice=4
    clear

if hash dotnet 2>/dev/null
then
    echo "Dotnet is installed."
    echo ""
else
    echo "Dotnet is not installed. Please install prerequisites (option 1)."
    exit 1
fi

    echo "1. Run Auto Restart and update EllieBot."
    echo "2. Run Auto Restart normally without updating EllieBot."
    echo "3. Exit"
    echo ""
    echo "Choose:"
    echo "[1] to Run with Auto Updating on restart after using \"die\" command."
    echo "[2] to Run EllieBot with Auto Restart on \"die\" command without updating."

while [ $choice -eq 4 ]; do
read choice
    if [ $choice -eq 1 ] ; then

        wget -q -N https://toastielab.dev/EllieBotDevs/ellie-bash-installer/raw/branch/v5/detectOS.sh
        bash detectOS.sh > /dev/null || exit $?

        echo ""
        echo "Running EllieBot with auto update. Please wait. . ."
        while :; do
        yt-dlp -U 2>/dev/null
	      cd "$root/elliebot"
            git fetch
            HEADHASH=$(git rev-parse HEAD)
            UPSTREAMHASH=$(git rev-parse @{u})

            if [[ "$HEADHASH" != "$UPSTREAMHASH" ]]; then
                echo "Update found, this may take a few minutes... "
                cd $root
                wget -N https://toastielab.dev/EllieBotDevs/ellie-bash-installer/raw/branch/v5/e-download.sh && bash "$root/e-download.sh"
                cd elliebot/output
                dotnet EllieBot.dll
            else
                echo "No updates found, starting the bot... "
                cd output
                dotnet EllieBot.dll
            fi
        done
    elif [ $choice -eq 2 ] ; then
        echo ""
        echo "Running EllieBot without auto update. Please wait. . ."
        while :; do cd "$root/elliebot/output" && dotnet EllieBot.dll && yt-dlp -U; sleep 5s; done
        echo "Done"
    elif [ "$choice" -eq 3 ] ; then
        echo ""
        echo "Exiting..."
        cd "$root"
        exit 0
    else
        echo "Invalid choice"
        sleep 3s
        echo ""
        clear
        echo "1. Run Auto Restart and update EllieBot."
        echo "2. Run Auto Restart normally without updating EllieBot."
        echo "3. Exit"
        echo ""
        echo "Choose:"
        echo "[1] to Run with Auto Updating on restart after using \"die\" command."
        echo "[2] to Run EllieBot with Auto Restart on \"die\" command without updating."
        choice=4
    fi
done

cd "$root"
rm "$root/e-are.sh"
exit 0