#!/bin/sh

# AM INSTALL SCRIPT VERSION 3.5
set -u
APP=i3lock-color
SITE="Raymo111/i3lock-color"

# CREATE DIRECTORIES AND ADD REMOVER
[ -n "$APP" ] && mkdir -p "/opt/$APP/tmp" "/opt/$APP/pam" && cd "/opt/$APP/tmp" || exit 1
printf "#!/bin/sh\nset -e\nrm -f /usr/local/bin/i3lock\nrm -R -f /opt/$APP" > ../remove
#printf '\n%s' "rm -f /usr/local/share/applications/$APP-AM.desktop" >> ../remove
chmod a+x ../remove || exit 1

# DOWNLOAD AND PREPARE THE APP, $version is also used for updates
version=$(curl -Ls https://api.github.com/repos/"$SITE"/releases | sed 's/[()",{} ]/\n/g' | grep -o 'https.*i3lock$' | head -1)
wget "$version" || exit 1
cd ..
mv ./tmp/* ./ || exit 1
rm -R -f ./tmp || exit 1
echo "$version" > ./version
chmod a+x ./i3lock || exit 1
cat >> ./pam/i3lock << 'EOF'
#
# PAM configuration file for the i3lock-color screen locker. By default, it includes
# the 'system-local-login' configuration file (see /etc/pam.d/system-local-login)
# for Arch and Gentoo and 'login' for Debian. Note that upstream uses only 'login',
# which doesn't work on Arch and Gentoo.
#

#auth include system-local-login # For Arch/Gentoo
auth include login # For Debian
EOF

# LINK TO PATH
cat >> /usr/local/bin/i3lock << 'EOF'
#!/bin/sh
APP=i3lock-color
cat /etc/pam.d/i3lock >/dev/null 2>&1 && "/opt/$APP/i3lock" "$@" || (
echo "You need to copy the i3lock pam file to /etc/pam.d for i3lock to work
That is: cp /opt/$APP/pam/i3lock /etc/pam.d/i3lock
MAKE SURE TO READ THE PAM FILE FIRST as it has to be configured for your distro.
If you are still getting this error there might be something wrong with i3lock." \
&& notify-send -u critical "Error i3lock: launch from terminal to see instructions" )
EOF
chmod a+x /usr/local/bin/i3lock

# SCRIPT TO UPDATE THE PROGRAM
cat >> ./AM-updater << 'EOF'
#!/bin/sh
set -u
APP=i3lock-color
SITE="Raymo111/i3lock-color"
version0=$(cat "/opt/$APP/version")
version=$(curl -Ls https://api.github.com/repos/"$SITE"/releases | sed 's/[()",{} ]/\n/g' | grep -o 'https.*i3lock$' | head -1)
[ -n "$version" ] || { echo "Error getting link"; exit 1; }
if [ "$version" != "$version0" ]; then
	mkdir "/opt/$APP/tmp" && cd "/opt/$APP/tmp" || exit 1
	notify-send "A new version of $APP is available, please wait"
	wget "$version" || exit 1
	cd ..
	mv ./tmp/* ./ || exit 1
	chmod a+x ./i3lock || exit 1
	echo "$version" > ./version
	rm -R -f ./tmp ./*~
	notify-send "$APP is updated!"
else
	echo "Update not needed!"
fi
EOF
chmod a+x ./AM-updater || exit 1