#!/bin/bash
# Set POSTINSTALL=1 to run postinst.sh and clean up discord's cache
# Set NOSANDBOX=1 to append --no-sandbox for Discord

is_fedora=$(cat /etc/os-release | grep -c Fedora)
has_libatomic=$(ldconfig -p | grep -c libatomic)
# pretty sure this was missing, on atleast Fedora
has_libsodium=$(ldconfig -p | grep -c libsodium)

if [ $has_libsodium = 0 ]
then
	echo "missing libsodium; install it to continue"
	exit 1
fi

if [ $NOSANDBOX ]
then
	nosandbox="--no-sandbox"
else
	nosandbox=""
fi

dl_discord () {
	echo "Downloading latest tar.gz"
	curl -L -s 'https://discord.com/api/download?platform=linux&format=tar.gz' |  tar xzf - -C /home/$USER/.local/share/
	echo "Writing discord.desktop"
	cat > /home/$USER/.local/share/applications/discord.desktop <<EOF
[Desktop Entry]
Name=Discord
StartupWMClass=discord
Comment=All-in-one voice and text chat for gamers that's free, secure, and works on both your desktop and phone.
GenericName=Internet Messenger
Exec=/home/$USER/.local/share/Discord/Discord $nosandbox
Icon=discord
Type=Application
Categories=Network;InstantMessaging;
EOF
	if [ $POSTINSTALL ]
	then
		echo "Running discord's post install"
		/home/$USER/.local/share/Discord/postinst.sh
	fi
	echo "Done"
}

case $is_fedora in
	0)
		dl_discord
		;;
	*)
		if [ $has_libatomic = 0 ]
		then
			echo "dnf install libatomic; to remove discord's warning"
		fi
		dl_discord
		;;
esac
