#!/bin/sh

# AM INSTALL SCRIPT VERSION 3.5
set -u
APP=avidemux-nightly
SITE="https://www.avidemux.org"

# CREATE DIRECTORIES AND ADD REMOVER
[ -n "$APP" ] && mkdir -p "/opt/$APP/tmp" "/opt/$APP/icons" && cd "/opt/$APP/tmp" || exit 1
printf "#!/bin/sh\nset -e\nrm -f /usr/local/bin/$APP\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="https://www.avidemux.org/nightly/appImage4/$(curl -Ls https://www.avidemux.org/nightly/appImage4/ | grep .app | grep -i mb | grep -o -P "(?<='./).*(?='>)" | tail -1)"
wget "$version" || exit 1
# Use tar fx ./*tar* here for example in this line in case a compressed file is downloaded.
cd ..
mv ./tmp/* ./"$APP"
rm -R -f ./tmp || exit 1
echo "$version" > ./version
chmod a+x ./"$APP" || exit 1

# LINK TO PATH
ln -s "/opt/$APP/$APP" "/usr/local/bin/$APP"

# SCRIPT TO UPDATE THE PROGRAM
cat >> ./AM-updater << 'EOF'
#!/bin/sh
set -u
APP=avidemux-nightly
SITE="https://www.avidemux.org"
version0=$(cat "/opt/$APP/version")
version="https://www.avidemux.org/nightly/appImage4/$(curl -Ls https://www.avidemux.org/nightly/appImage4/ | grep .app | grep -i mb | grep -o -P "(?<='./).*(?='>)" | tail -1)"
[ -n "$version" ] || { echo "Error getting link"; exit 1; }
if [ "$version" != "$version0" ] || [ -e /opt/"$APP"/*.zsync ]; then
	mkdir "/opt/$APP/tmp" && cd "/opt/$APP/tmp" || exit 1
	wget "$version" || exit 1
	cd ..
	mv --backup=t ./tmp/* ./"$APP"
	chmod a+x ./"$APP" || exit 1
	echo "$version" > ./version
	rm -R -f ./*zs-old ./*.part ./tmp ./*~
	notify-send "$APP is updated!"
else
	echo "Update not needed!"
fi
EOF
chmod a+x ./AM-updater || exit 1

# LAUNCHER & ICON
wget "https://raw.githubusercontent.com/mean00/avidemux2/master/avidemux_icon.png" -O ./icons/"$APP"
echo "[Desktop Entry]
Name=Avidemux
GenericName=Video Editor
Comment=Multiplatform video editor
Exec=$APP %f
Icon=/opt/$APP/icons/$APP
Terminal=false
Type=Application
Categories=AudioVideo;AudioVideoEditing;Video;
MimeType=video/mpeg;video/x-mpeg;video/mp4;video/x-m4v;video/quicktime;video/3gp;video/mkv;video/x-matroska;video/webm;video/flv;video/x-flv;video/dv;video/x-msvideo;video/x-ms-wmv;video/x-ms-asf;video/x-anim;" > /usr/local/share/applications/"$APP"-AM.desktop