#!/bin/bash
# Elevate script
if [ ! "$UID" -eq 0 ]
then
    sudo bash "$BASH_SOURCE" "$USER";
else
    tempDir="$(mktemp -d)";
    archiveName="$(mktemp)";
    destination="/var/lib/godot";

    if [ -d "$destination" ]
    then
        rm -rf "$destination";
    fi

    wget https://github.com/godotengine/godot/releases/download/4.0-stable/Godot_v4.0-stable_mono_linux_x86_64.zip -O "$archiveName";
    unzip "$archiveName" -d "$tempDir";
    mkdir -p "$destination";
    mv "$tempDir"/*/* "$destination";
    wget https://github.com/godotengine/godot/raw/4.0-stable/icon.svg -O "$destination/icon.svg";

    rm -rf "$tempDir";
    rm -f "$archiveName";

    exeFile="$(find "$destination" -maxdepth 1 -perm -111 -type f)";
    ln -fs "$exeFile" /usr/local/bin/godot;

    {
        echo "[Desktop Entry]";
        echo "Encoding=UTF-8";
        echo "Type=Application";
        echo "Terminal=false";
        echo "Exec=$exeFile";
        echo "Name=Godot Engine";
        echo "Icon=$destination/icon.svg";
    } > /usr/share/applications/godot.desktop;
fi