#!/bin/bash

# Versions: 
# Install script: 1.4
# Lastest change: Use my own tmp/ folder instead to avoid permission problems
# Launcher: 2021.0

# Method to check if a command exist
command_exists () {
    type "$1" > /dev/null ;
}

# Check if curl is installed
if command_exists sudo; then
    sudo apt install curl -y
else
    echo "WARNING: sudo IS NOT RECOGNIZED YOU MIGHT HAVE SOME PROBLEMS INSTALLING THE LAUNCHER IF YOU AREN'T ROOT"
    apt install curl -y
fi

# Check if said folder exist, if not, create it
if [ ! -d ~/.local/share/applications ]; then
    mkdir -p ~/.local/share/applications
fi
if [ ! -d ~/.icons ]; then
    mkdir ~/.icons
fi
if [ ! -d ~/.backtobeta ]; then
    mkdir ~/.backtobeta/
fi
if [ ! -d ~/.backtobeta/tmp ]; then
    mkdir ~/.backtobeta/tmp/
fi
if [ ! -d ~/.backtobeta/Launcher ]; then
    mkdir ~/.backtobeta/Launcher/
fi

# Download java JRE 1.8 & Extract it
echo "Downloading java..."
if [ -d ~/.backtobeta/Launcher/jre1.8.0_261 ]; then
    # EDIT THIS LINE IF ONLY YOU KNOW WHAT YOU'RE DOING !
    rm -rf ~/.backtobeta/Launcher/jre1.8.0_261/
fi
curl -o ~/.backtobeta/tmp/java.tar.gz https://www.krafting.net/0/backtobeta/dl/data/java.tar.gz
tar -xf ~/.backtobeta/tmp/java.tar.gz 
mv -fvu jre1.8.0_261/ ~/.backtobeta/Launcher/

echo "Downloading the launcher and adding a Menu entry..."

# Download the launcher itself
curl -o ~/.backtobeta/tmp/LauncherBTB.jar https://www.krafting.net/0/backtobeta/dl/data/LauncherBTB.jar
mv -fv ~/.backtobeta/tmp/LauncherBTB.jar ~/.backtobeta/Launcher/

# Download the .desktop file & icon and move it on the ~/.local/share/applications/
curl -o ~/.backtobeta/tmp/btb.png https://www.krafting.net/0/backtobeta/dl/data/logo.png
mv -fv ~/.backtobeta/tmp/btb.png ~/.icons 

# Downloading & Moving of the menu entry
curl -o ~/.backtobeta/tmp/BackToBeta.desktop https://www.krafting.net/0/backtobeta/dl/data/BTB.desktop
mv -fv ~/.backtobeta/tmp/BackToBeta.desktop ~/.local/share/applications/
printf "\nIcon=$HOME/.icons/btb.png" >> ~/.local/share/applications/BackToBeta.desktop

# Create the launch script for better control of the .desktop
echo "~/.backtobeta/Launcher/jre1.8.0_261/bin/java -jar ~/.backtobeta/Launcher/LauncherBTB.jar" > ~/.backtobeta/Launcher/launch.sh
chmod +x ~/.backtobeta/Launcher/launch.sh
chmod +x ~/.backtobeta/Launcher/LauncherBTB.jar
chmod +x ~/.local/share/applications/BackToBeta.desktop

if [ ! -d ~/.backtobeta/tmp ]; then
    rm -rf ~/.backtobeta/tmp/
fi
echo ""
echo "Back To Beta a été installé avec succès. Lancé le depuis votre menu."

