#!/bin/sh

APP=btop
REPO="aristocratos/btop"

# CREATE DIRECTORIES
if [ -z "$APP" ]; then exit 1; fi
mkdir -p "/opt/$APP/tmp" "/opt/$APP/icons" && cd "/opt/$APP/tmp" || exit 1

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

# DOWNLOAD AND PREPARE THE APP
# $version is also used for updates

version=$(curl -Ls https://api.github.com/repos/"$REPO"/releases/latest | grep browser_download_url | grep aarch64 | cut -d '"' -f 4 | head -1)
wget "$version"
tar xf ./*.tbz
cd ..
echo "$version" >> ./version
mv ./tmp/*/* ./
ln -s ./bin/btop ./"$APP"
chmod a+x ./bin/btop
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'
#!/bin/sh
APP=btop
REPO="aristocratos/btop"
version0=$(cat /opt/$APP/version)
version=$(curl -Ls https://api.github.com/repos/"$REPO"/releases/latest | grep browser_download_url | grep aarch64 | cut -d '"' -f 4 | head -1)
if [ "$version" = "$version0" ]; then
	echo "Update not needed!" || exit 0
else
	notify-send "A new version of $APP is available, please wait"
	mkdir /opt/$APP/tmp && cd /opt/$APP/tmp || exit 1
	wget "$version"
	tar xf ./*.tbz
	cd ..
	rm ./version
  	echo "$version" >> ./version
  	mv --backup=t ./tmp/*/* ./
	chmod a+x ./bin/btop
  	rm -R -f ./tmp ./*~
	notify-send "$APP is updated!"
fi
EOF
chmod a+x "/opt/$APP/AM-updater"

# LAUNCHER & ICON
mv ./*.desktop /usr/local/share/applications/"$APP"-AM.desktop && mv ./*mg/*.svg ./icons/btop 2>/dev/null #btop already ships the files
