#!/bin/bash

# DOC: Requires:
# https://github.com/AppImage/AppImageKit
# https://github.com/linuxdeploy/linuxdeploy
# https://github.com/linuxdeploy/linuxdeploy-plugin-qt

set -eu

if [ ! -f "src/kshutdown.desktop" ]; then
	echo "USAGE: ./tools/make-app-image.sh"
	exit 1
fi

# HACK: may not work with ext4+ecryptfs
APPDIRTMP="$(mktemp -d --tmpdir kshutdown.XXXXX)"

function cleanup() {
	echo "INFO: Removing $APPDIRTMP..."

	rm -fr "$APPDIRTMP"
}

trap cleanup EXIT

echo "INFO: Using temporary directory: $APPDIRTMP"

APPDIR="$APPDIRTMP/KShutdown.AppDir"
APPIMAGE="dist/KShutdown.AppImage"
APPIMAGE_DESKTOP_FILE="$APPDIRTMP/kshutdown.desktop"

echo "INFO: Patching $APPIMAGE_DESKTOP_FILE file..."

cp -v src/kshutdown.desktop "$APPIMAGE_DESKTOP_FILE"
sed -i "s?Icon=system-reboot?Icon=kshutdown.png?g" "$APPIMAGE_DESKTOP_FILE"

echo "INFO: Creating $APPDIR..."

linuxdeploy-x86_64.AppImage \
	--appdir "$APPDIR" \
	--desktop-file "$APPIMAGE_DESKTOP_FILE" \
	--executable src/kshutdown \
	--icon-file src/images/hi16-app-kshutdown.png \
	--icon-file src/images/hi22-app-kshutdown.png \
	--icon-file src/images/hi32-app-kshutdown.png \
	--icon-file src/images/hi48-app-kshutdown.png \
	--icon-file src/images/hi64-app-kshutdown.png \
	--icon-file src/images/hi128-app-kshutdown.png \
	--icon-filename kshutdown \
	--plugin qt

echo "INFO: Creating $APPIMAGE..."

mkdir -p "dist"
appimagetool-x86_64.AppImage \
	--comp gzip \
	"$APPDIR" \
	"$APPIMAGE"
