#!/bin/sh

APP=supertuxkart
REPO="supertuxkart/stk-code"

# CREATE THE FOLDER
mkdir /opt/$APP
cd /opt/$APP

# ADD THE REMOVER
echo '#!/bin/sh' >> /opt/$APP/remove
echo "rm -R -f /usr/local/share/applications/$APP-AM.desktop /opt/$APP /usr/local/bin/$APP" >> /opt/$APP/remove
chmod a+x /opt/$APP/remove

# DOWNLOAD THE ARCHIVE
mkdir tmp
cd ./tmp

version=$(curl -Ls https://api.github.com/repos/$REPO/releases | grep browser_download_url | echo "$(if grep -i linux-arm64.tar.xz; then echo linux-arm64.tar.xz; else echo linux-aarch64.tar.xz; fi)" | cut -d '"' -f 4 | head -1)
wget $version
echo "$version" >> /opt/$APP/version
cd ..
tar fx ./tmp/*tar.xz -C ./tmp/ && rm -R ./tmp/*tar.xz && mv ./tmp/Super*/* . && mv ./run_game.sh ./$APP && cp ./data/*512.png . && cp ./data/*.desktop .
rm -R -f ./tmp

# LINK
ln -s /opt/$APP/$APP /usr/local/bin/$APP

# SCRIPT TO UPDATE THE PROGRAM
cat >> /opt/$APP/AM-updater << 'EOF'
#!/usr/bin/env bash
APP=supertuxkart
REPO="supertuxkart/stk-code"
version0=$(cat /opt/$APP/version)
version=$(curl -Ls https://api.github.com/repos/$REPO/releases | grep browser_download_url | echo "$(if grep -i linux-arm64.tar.xz; then echo linux-arm64.tar.xz; else echo linux-aarch64.tar.xz; fi)" | cut -d '"' -f 4 | head -1)
if [ $version = $version0 ]; then
  echo "Update not needed!"
else
  notify-send "A new version of $APP is available, please wait"
  mkdir /opt/$APP/tmp
  cd /opt/$APP/tmp
  wget $version
  cd ..
  tar fx ./tmp/*tar.xz -C ./tmp/ && rm -R ./tmp/*tar.xz && mv ./tmp/Super*/* . && mv ./run_game.sh ./$APP && cp ./data/*512.png . && cp ./data/*.desktop .
  rm ./version
  echo $version >> ./version
  rm -R -f ./tmp ./*~
  notify-send "$APP is updated!"
fi
EOF
chmod a+x /opt/$APP/AM-updater

# LAUNCHER & ICON
app=$(echo $APP | cut -c -3)
cd /opt/$APP
mv ./*.desktop ./$APP.desktop 2>/dev/null
CHANGEEXEC=$(cat ./$APP.desktop | grep Exec= | tr ' ' '\n' | tr '=' '\n' | tr '/' '\n' | grep $app | head -1)
sed -i "s#$CHANGEEXEC#$APP#g" ./$APP.desktop
sed -i "s#Exec=/bin/#Exec=#g" ./$APP.desktop
sed -i "s#Exec=/usr/bin/#Exec=#g" ./$APP.desktop
CHANGEICON=$(cat ./$APP.desktop | grep Icon= | head -1)
sed -i "s#$CHANGEICON#Icon=/opt/$APP/icons/$APP#g" ./$APP.desktop

mkdir icons
mv ./*.svg ./icons/$APP 2>/dev/null
mv ./*.png ./icons/$APP 2>/dev/null
mv ./*$app*.png ./icons/$APP 2>/dev/null
mv ./*128*.png ./icons/$APP 2>/dev/null
mv ./*256*.png ./icons/$APP 2>/dev/null

mv ./$APP.desktop /usr/local/share/applications/$APP-AM.desktop
