#!/bin/bash
# NOTE: This build is NOT a fork BUT it does use a custom native library repo for the arm64/armhf builds, which is necessary as microsoft and the multimc5 devs do not provide arm64/armhf native libraries

# obtain the cpu and os info
get_model
# Remove dummy OEM info.
model=${model//To be filled by O.E.M./}
model=${model//To Be Filled*/}
model=${model//OEM*/}
model=${model//Not Applicable/}
model=${model//System Product Name/}
model=${model//System Version/}
model=${model//Undefined/}
model=${model//Default string/}
model=${model//Not Specified/}
model=${model//Type1ProductConfigId/}
model=${model//INVALID/}
model=${model//All Series/}
model=${model//�/}

status "Installing Necessary Dependencies"
case "$__os_id" in
# Raspbian is not reported as a derivative of Debian (no /etc/upstream-release/lsb-release file)
Raspbian | Debian)
  if printf '%s\n' "10" "$__os_release" | sort -CV; then
    adoptium_installer || exit 1
    install_packages temurin-8-jre temurin-17-jdk || exit 1
    java_home="$(dpkg -L temurin-17-jdk | grep "/usr/lib/jvm.*$(dpkg --print-architecture)$")"
  else
    error "Debian version ($__os_codename) is too old, update to debian Buster or newer"
  fi
  ;;
Kali)
  adoptium_installer || exit 1
  install_packages temurin-8-jre temurin-17-jdk || exit 1
  java_home="$(dpkg -L temurin-17-jdk | grep "/usr/lib/jvm.*$(dpkg --print-architecture)$")"
  ;;
Ubuntu)
  # ubuntu default repositories now include openjdk-17
  # install java
  install_packages openjdk-8-jre openjdk-17-jdk || exit 1
  java_home="$(dpkg -L openjdk-17-jdk | grep "/usr/lib/jvm.*$(dpkg --print-architecture)$")"
  ;;
*)
  error "$__os_id appears to be an unsupported OS"
  ;;
esac

# install normal dependencies
install_packages build-essential libopenal1 x11-xserver-utils subversion git clang cmake curl zlib1g-dev qtbase5-dev mesa-utils || error "Failed to install dependencies on $__os_codename"

hash -r

# make all the folders
cd "$HOME"
mkdir -p "$HOME/MultiMC"
cd "$HOME/MultiMC" || error "Could not move to directory"
mkdir -p build
mkdir -p install
# clone the complete source
status "Downloading the MultiMC5 Source Code directly from the official repository..."
git clone --recursive https://github.com/MultiMC/Launcher.git src
cd src || error "Could not move to directory"
git remote set-url origin https://github.com/MultiMC/Launcher.git
git checkout --recurse-submodules develop || error "Could not checkout develop branch"
git pull --recurse-submodules || error "Could Not Pull Latest MultiMC Source Code, verify your ~/MultiMC/src directory hasn't been modified. You can detete the  ~/MultiMC/src folder to attempt to fix this error and run this script again."
git checkout --recurse-submodules d98022d3ae43bf07546d33beb2013c1ede14a4f8 || error "Could Not Checkout MultiMC Source Code commit, verify your ~/MultiMC/src directory hasn't been modified. You can detete the  ~/MultiMC/src folder to attempt to fix this error and run this script again."
# add secrets files
mkdir -p secrets
tee secrets/Secrets.h <<'EOF' >>/dev/null
#pragma once
#include <QString>
#include <cstdint>
namespace Secrets {
bool hasMSAClientID();
QString getMSAClientID(uint8_t separator);
}
EOF

tee secrets/Secrets.cpp <<'EOF' >>/dev/null
#include "Secrets.h"
#include <array>
#include <cstdio>
namespace Secrets {
bool hasMSAClientID() {
    return true;
}
QString getMSAClientID(uint8_t separator) {
    return "81a207c0-a53c-46a3-be07-57d2b28c1643";
}
}
EOF

tee secrets/CMakeLists.txt <<'EOF' >>/dev/null
add_library(secrets STATIC Secrets.cpp Secrets.h)
target_link_libraries(secrets Qt5::Core)
target_compile_definitions(secrets PUBLIC -DEMBED_SECRETS)
target_include_directories(secrets PUBLIC .)

set(Launcher_CommonName "MultiMC")

set(Launcher_Copyright "MultiMC Contributors" PARENT_SCOPE)
set(Launcher_Domain "multimc.org" PARENT_SCOPE)
set(Launcher_Name "${Launcher_CommonName}" PARENT_SCOPE)
set(Launcher_DisplayName "${Launcher_CommonName} 5" PARENT_SCOPE)
set(Launcher_UserAgent "${Launcher_CommonName}/5.0" PARENT_SCOPE)
set(Launcher_ConfigFile "multimc.cfg" PARENT_SCOPE)
set(Launcher_Git "https://github.com/MultiMC/Launcher" PARENT_SCOPE)

set(Launcher_Branding_ICNS "notsecrets/Launcher.icns" PARENT_SCOPE)
set(Launcher_Branding_WindowsRC "notsecrets/launcher.rc" PARENT_SCOPE)
set(Launcher_Branding_LogoQRC "notsecrets/logo.qrc" PARENT_SCOPE)
EOF

cd ..
# configure the project
cd build
# obtain the cpu info
get_system
# temporary hotfix to build with java 11 (build currently fails on java 16 autodetection)
# https://github.com/MultiMC/Launcher/issues/3949
# remove cmake cache until bug is fixed
rm -rf CMakeCache.txt
status "Generating the CMake File"
case "$arch" in
"64") cmake -DLauncher_EMBED_SECRETS=ON -DJAVA_HOME="$java_home" -DLauncher_BUILD_PLATFORM="$model" -DLauncher_BUG_TRACKER_URL="https://github.com/Botspot/pi-apps/issues" -DLauncher_DISCORD_URL="https://discord.gg/RXSTvaUvuu" -DCMAKE_INSTALL_PREFIX=../install -DLauncher_META_URL:STRING="https://raw.githubusercontent.com/theofficialgman/meta-multimc/master-clean/index.json" ../src || error "cmake failed to generate" ;;
"32") cmake -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DLauncher_EMBED_SECRETS=ON -DJAVA_HOME="$java_home" -DLauncher_BUILD_PLATFORM="$model" -DLauncher_BUG_TRACKER_URL="https://github.com/Botspot/pi-apps/issues" -DLauncher_DISCORD_URL="https://discord.gg/RXSTvaUvuu" -DCMAKE_INSTALL_PREFIX=../install -DLauncher_META_URL:STRING="https://raw.githubusercontent.com/theofficialgman/meta-multimc/master-clean-arm32/index.json" ../src || error "cmake failed to generate" ;;
*) error "Failed to detect OS CPU architecture! Something is very wrong." ;;
esac

warning "MultiMC5 does not give support for custom builds"
warning "Only bugs that can be reproduced on official MultiMC5 builds should be posted to https://github.com/MultiMC/MultiMC5/issues"
warning "Bugs which only appear on this build should be posted to https://github.com/cobalt2727/L4T-Megascript/issues"

# build & install (use -j with the number of cores your CPU has)
status "Starting Compilation"
make -j$(nproc) install || error "Make install failed"

cd .. || error "Could not move to directory"
# add Jvm Arguments for increased performance
# these can always be overwritten by the user after the first installation
if cat install/multimc.cfg | grep -q "JvmArgs="; then
  if cat install/multimc.cfg | grep -q "JvmArgs=."; then
    warning "Skipping Adding JvmArgs as they are already populated by the user or a previous installation"
    status "The current JvmArgs are set to: $(cat install/multimc.cfg | grep "JvmArgs=")"
  else
    status "Adding JvmArgs which help with performance overall in all minecraft versions"
    sed -i "s/JvmArgs=.*/JvmArgs=-XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1/g" install/multimc.cfg
  fi
else
  status "Adding JvmArgs which help with performance overall in all minecraft versions"
  echo "JvmArgs=-XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1" >>install/multimc.cfg
fi

cd
mkdir -p ~/.local/share/applications
mkdir -p ~/.local/share/icons/MultiMC
# copy icon to .local folder
cp "${DIRECTORY}/apps/Minecraft Java MultiMC5/icon-64.png" "$HOME/.local/share/icons/MultiMC/icon-64.png"

function version { echo "$@" | awk -F. '{ printf("%d%03d%03d\n", $1,$2,$3); }'; }
# detect if script is running on a system with OpenGL lower than 3.3
if [ $(version $(glxinfo -B | sed -n "s/^OpenGL version string://p" | awk '{ print $1 }')) -lt $(version "3.3.0") ]; then
  warning "You are running a device that is not OpenGL 3.3 compliant or the OpenGL version could not be determined."
  warning "Adding a MESA_GL_VERSION_OVERRIDE to 3.3"
  warning "Vannilla up to 1.19.1 has been tested to work on Raspberry PI but there is no guarantee that future Minecraft versions and mods like Sodium/Optifine will continute to work."
  sh -c "cat > ~/.local/share/applications/MultiMC.desktop << _EOF_
[Desktop Entry]
Type=Application
Exec=env MESA_GL_VERSION_OVERRIDE=3.3 QT_AUTO_SCREEN_SCALE_FACTOR=0 $HOME/MultiMC/install/MultiMC
Hidden=false
NoDisplay=false
Name=MultiMC
Icon=$HOME/.local/share/icons/MultiMC/icon-64.png
Categories=Game
_EOF_"
else
  sh -c "cat > ~/.local/share/applications/MultiMC.desktop << _EOF_
[Desktop Entry]
Type=Application
Exec=$HOME/MultiMC/install/MultiMC
Hidden=false
NoDisplay=false
Name=MultiMC
Icon=$HOME/.local/share/icons/MultiMC/icon-64.png
Categories=Game
_EOF_"
fi
status_green 'Installation is now done! You can open the launcher by going to Menu > Games > MultiMC'

warning "The upstream, MultiMC5, does not give support for custom builds"
warning "Bugs which appear on this build should only be posted to https://github.com/Botspot/pi-apps/issues or ask for help in the Pi-Apps Discord Server"
status "Make sure to visit the upstream wiki if this is your first time using the launcher: https://github.com/MultiMC/MultiMC5/wiki"
status "If you need help installing Optifine: https://github.com/MultiMC/MultiMC5/wiki/MultiMC-and-OptiFine"
status "How to choose the correct java version: https://github.com/MultiMC/Launcher/wiki/Using-the-right-Java#setting-up-java-in-multimc"
