#!/bin/bash

# install box86
"${DIRECTORY}/manage" install-if-not-installed Box86 || error "Box86 failed to install somehow!"
# install box64
"${DIRECTORY}/manage" install-if-not-installed Box64 || error "Box64 failed to install somehow!"

# add additional packages not already installed by box86/box64
install_packages libnss3:armhf libnm0:armhf libdbus-glib-1-2:armhf libnspr4:armhf libgudev-1.0-0:armhf libxtst6:armhf libsm6:armhf libice6:armhf libusb-1.0-0:armhf libnss3 libnm0 libdbus-glib-1-2 libudev1 libnspr4 libgudev-1.0-0 libxtst6 libsm6 libice6 libusb-1.0-0 || exit 1

# perform an apt upgrade to make sure the latest version of box64 and box86 are installed
apt_lock_wait
sudo apt upgrade -y || exit 1

if package_installed steam-devices ; then
  echo "Removing steam-devices package because it conflicts with steam-launcher..."
  apt_lock_wait
  sudo apt purge -y steam-devices
fi

if package_installed steamlink ; then
  echo "Removing steamlink package because it conflicts with steam-launcher..."
  apt_lock_wait
  sudo apt purge -y steamlink
fi

echo "Installing steam_latest.deb"
install_packages https://repo.steampowered.com/steam/archive/stable/steam_latest.deb || exit 1

sudo mkdir -p /usr/local/bin /usr/local/share/applications
# if a matching name binary is found in /usr/local/bin it takes priority over /usr/bin
echo '#!/bin/bash
export STEAMOS=1
export STEAM_RUNTIME=1
export DBUS_FATAL_WARNINGS=0
BOX64_LOG=1 BOX86_LOG=1 BOX64_EMULATED_LIBS=libmpg123.so.0 /usr/lib/steam/bin_steam.sh -no-cef-sandbox steam://open/minigameslist "$@"

rm -f /home/${USER}/Desktop/steam.desktop' | sudo tee /usr/local/bin/steam || error "Failed to create steam launch script"

# set execution bit
sudo chmod +x /usr/local/bin/steam

# copy official steam.desktop file to /usr/local and edit it
# we can't edit the official steam.desktop file since this will get overwritten on a steam update
# if a matching name .desktop file is found in /usr/local/share/applications it takes priority over /usr/share/applications
sudo cp /usr/share/applications/steam.desktop /usr/local/share/applications/steam.desktop
sudo sed -i 's:Exec=/usr/bin/steam:Exec=/usr/local/bin/steam:' /usr/local/share/applications/steam.desktop

# remove deb
rm /tmp/steam.deb
rm -f /home/${USER}/Desktop/steam.desktop

if ! echo "$XDG_DATA_DIRS" | grep -q "/usr/local/share" || ! echo "$PATH" | grep -q "/usr/local/bin" ; then
  warning "YOU NEED TO REBOOT before starting steam. This is because Steam is the first application on your system to be installed into the /usr/local folder."
else
  warning "You should restart your system before trying to launch Steam otherwise errors may occur."
fi
