#!/bin/bash

set -xeo pipefail

# Variables
APP=Steam-x86_64.AppImage
NAME=steam
URL="https://github.com/ivan-hc/Steam-appimage/releases/download/continuous/Steam-202310201446-x86_64.AppImage"
LOCAL_BIN_DIR=$HOME/.local/bin
DESKTOP_DIR=$HOME/.local/share/applications

# Ensure local bin directory is in PATH
if [[ ! ":$PATH:" == *":$LOCAL_BIN_DIR:"* ]]; then
    echo "export PATH=\$PATH:$LOCAL_BIN_DIR" >> $HOME/.bashrc
    echo "export PATH=\$PATH:$LOCAL_BIN_DIR" >> $HOME/.bash_profile
fi

# Install Steam AppImage
cd /tmp
curl -LO $URL
chmod +x $APP
./$APP --appimage-extract
mv squashfs-root $HOME/$NAME

# Create symbolic link to AppRun
ln -sf $(realpath $HOME/$NAME/AppRun) $LOCAL_BIN_DIR/$NAME

# Install desktop entry
desktop-file-install --dir="$DESKTOP_DIR" $HOME/$NAME/$NAME.desktop

# Update desktop entry
sed -i "s|Exec=$NAME|Exec=$LOCAL_BIN_DIR/$NAME|g" $DESKTOP_DIR/$NAME.desktop

# Mark desktop entry as trusted
gio set "$DESKTOP_DIR/$NAME.desktop" "metadata::trusted" true

# Clean up
rm -rf /tmp/$APP