#!/bin/sh
#
# Spk-appimage - Install and manage AppImages in user space. Read the
# README before adding or modifying any code in spk!
#
# An AppImage is one self-contained executable file: it is stored in
# ~/Applications, linked as a command in ~/.local/bin and a menu entry is
# written in ~/.local/share/applications. No root, no package database:
# everything happens with the rights of the user who installs.
#
# The menu entry comes from the .desktop file embedded in the image (Exec
# and TryExec rewritten to the installed file), the icon from the image's
# .DirIcon. FUSE is only needed to run, not to install: without /dev/fuse
# the entry runs the image with --appimage-extract-and-run (slower).
#
# Copyright (C) SliTaz GNU/Linux - BSD License
# Author: See AUTHORS files
#
. /lib/libtaz.sh

# Our messages live in spk.mo, installed by spk.
export TEXTDOMAIN='spk'

VERSION=0.1

# User space paths (XDG): nothing under /usr or /var.
appsdir="$HOME/Applications"
bindir="$HOME/.local/bin"
datadir="${XDG_DATA_HOME:-$HOME/.local/share}"
dbdir="$datadir/spk-appimage"
menudir="$datadir/applications"
icondir="$datadir/icons/hicolor"
tmpdir="${TMPDIR:-/tmp}/spk-appimage.$$"

# No colour or cursor escapes when not a terminal (pipe, tests, GUI).
[ -t 1 ] || : ${output:=raw}

[ "$HOME" ] || die "HOME is not set"

#
# Functions
#

# Help and usage
usage() {
	name=$(basename $0)
	cat << EOT

$(boldify $(gettext "Usage:")) $name [command] [file|name] [--options]

$(gettext "Install and manage AppImages in user space (no root)") v$VERSION

$(boldify $(gettext "Commands:"))
  info        $(gettext "Show AppImage information before installing it")
  install     $(gettext "Install an AppImage (local file or URL)")
  list        $(gettext "List installed AppImages (--raw, --trame)")
  remove      $(gettext "Remove installed AppImages")
  run         $(gettext "Run an installed AppImage")

$(boldify $(gettext "Options:"))
  --name=     $(gettext "Install name (default: the application name)")
  --force     $(gettext "Replace an already installed AppImage")
  --no-desktop $(gettext "Do not create the menu entry")
  --raw       $(gettext "Flat TSV output")
  --trame     $(gettext "Single JSON object output")
  --debug     $(gettext "Display some useful debug information")

$(boldify $(gettext "Paths:"))
  $(gettext "AppImages:") $appsdir
  $(gettext "Commands:")  $bindir
  $(gettext "Menu:")      $menudir

$(boldify $(gettext "Examples:"))
  $name info ~/Downloads/Foo.AppImage
  $name install ~/Downloads/Foo.AppImage --name=foo
  $name list

EOT
	exit 0
}

# Temporary directory, always removed on exit (and the extracted copy of
# a non executable source with it).
cleanup() {
	[ -d "$tmpdir" ] && rm -rf "$tmpdir"
}
trap cleanup EXIT HUP INT TERM

tmpinit() {
	[ -d "$tmpdir/extract" ] && return
	mkdir -p "$tmpdir/extract" || die "Cannot create %s" "$tmpdir"
}

# Absolute path: the runtime is called from inside the temporary directory.
abs_path() {
	case "$1" in
		/*) printf '%s' "$1" ;;
		*)  printf '%s' "$PWD/$1" ;;
	esac
}

# AppImage magic: ELF header, bytes 8-10 are 'A' 'I' and the type, 1 for
# the old ISO format (refused), 2 for squashfs. The ELF class (byte 4) is
# only a warning: the kernel may still run a 32-bit image.
check_image() {
	local img="$1" magic aimagic class
	if [ ! -f "$img" ]; then
		gettext "Not a file:"; echo " $img"
		return 1
	fi
	magic=$(dd if="$img" bs=1 count=4 2>/dev/null | od -An -tx1 | tr -d ' \n')
	if [ "$magic" != "7f454c46" ]; then
		gettext "Not an ELF file:"; echo " $img"
		return 1
	fi
	aimagic=$(dd if="$img" bs=1 skip=8 count=3 2>/dev/null | \
		od -An -tx1 | tr -d ' \n')
	case "$aimagic" in
		414902) ;;
		414901)
			gettext "AppImage type 1 (ISO image) is not supported:"
			echo " $img"; return 1 ;;
		*)
			gettext "Not an AppImage (no AppImage magic):"
			echo " $img"; return 1 ;;
	esac
	class=$(dd if="$img" bs=1 skip=4 count=1 2>/dev/null | \
		od -An -tx1 | tr -d ' \n')
	case "$(uname -m)-$class" in
		x86_64-02|i?86-01|arm*-01|armv?-01) ;;
		*) gettext "WARNING: the image architecture may not match this system."
			newline ;;
	esac
	return 0
}

# The runtime must be executable to run --appimage-extract. Extract from a
# copy when the source lacks the bit: never change the caller's file.
work_image() {
	wimg="$1"
	wcopy=
	if [ ! -x "$wimg" ]; then
		mkdir -p "$tmpdir/work"
		wcopy="$tmpdir/work/$(basename "$wimg")"
		cp -f "$wimg" "$wcopy" || die "Cannot copy %s" "$wimg"
		chmod 755 "$wcopy"
		wimg="$wcopy"
	fi
}

# Extract one pattern from the image. The runtime takes a single pattern
# per call and writes ./squashfs-root in the current directory.
img_extract() {
	debug "extract '$2'"
	( cd "$tmpdir/extract" && "$1" --appimage-extract "$2" ) >/dev/null 2>&1
}

# Read a key from a .desktop file. Never sourced: the file comes from the
# image and any line in it would run.
deskval() {
	awk -F= -v k="$1" '$1 == k { sub(/^[^=]*=/, ""); print; exit }' "$2" | \
		tr -d '\r'
}

# Best icon of the extracted tree: the biggest PNG, else an SVG. Small
# panels render SVG icons black, so PNG always wins.
pick_icon() {
	local t="$1" list f size best= bestsize=-1
	list="$tmpdir/icons.list"
	find "$t" -type f -name '*.png' 2>/dev/null > "$list"
	[ -s "$list" ] || find "$t" -type f -name '*.svg' 2>/dev/null > "$list"
	while IFS= read -r f; do
		case "$f" in
			*.svg) size=0 ;;
			*) size=$(printf '%s' "$f" | \
				sed -n 's|.*/\([0-9][0-9]*\)x[0-9][0-9]*/.*|\1|p') ;;
		esac
		[ "$size" ] || size=0
		[ "$size" -ge "$bestsize" ] && bestsize=$size best=$f
	done < "$list"
	printf '%s' "$best"
}

# Same as spk-convert: escape what is special in a double-quoted shell
# string, our .info file is sourced by list, info and remove.
esc() { printf '%s' "$1" | sed 's/[\\"`$]/\\&/g'; }

# Escape a sed replacement and the | delimiter.
sedsafe() { printf '%s' "$1" | sed 's/[\\&|]/\\&/g'; }

# Escape a JSON string value.
json_esc() {
	printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/	/\\t/g'
}

# FUSE is needed to run an image without extracting it first.
have_fuse() {
	[ -e /dev/fuse ] || return 1
	command -v fusermount >/dev/null 2>&1
}

# Human size of a file, for display only.
hsize() {
	du -h "$1" 2>/dev/null | awk '{print $1}'
}

# Install name: lowercase, no space, safe in a path and in a shell.
slugify() {
	printf '%s' "$1" | tr 'A-Z' 'a-z' | \
		sed -e 's/[^a-z0-9._-]\+/-/g' -e 's/^-*//' -e 's/-*$//'
}

# Fallback version: the last dotted number of the file name.
guess_ver() {
	basename "$1" | sed 's/\.AppImage$//' | tr '-_' '  ' | tr ' ' '\n' | \
		grep -E '^[0-9]+(\.[0-9]+)+$' | tail -n 1
}

# Extract and read the metadata of an image. Sets:
# m_desktop m_deskid m_name m_version m_cats m_exec m_iconname m_icon m_class
meta_read() {
	local src="$1" t="$tmpdir/extract/squashfs-root" icon class
	unset m_desktop m_deskid m_name m_version m_cats m_exec m_iconname m_icon \
		m_class

	img_extract "$src" '*.desktop'
	set -- "$t"/*.desktop
	if [ -f "$1" ]; then
		m_desktop="$1"
	else
		m_desktop=$(find "$t" -type f -name '*.desktop' 2>/dev/null | \
			head -n 1)
	fi
	[ -f "$m_desktop" ] || return 1

	m_deskid=$(basename "$m_desktop" .desktop)
	m_name=$(deskval Name "$m_desktop")
	m_version=$(deskval X-AppImage-Version "$m_desktop")
	m_cats=$(deskval Categories "$m_desktop")
	m_exec=$(deskval Exec "$m_desktop")
	m_iconname=$(deskval Icon "$m_desktop")

	# .DirIcon is the canonical icon, often a symlink to the real file.
	img_extract "$src" '.DirIcon'
	icon="$t/.DirIcon"
	if [ -L "$icon" ]; then
		icon=$(readlink "$icon")
		img_extract "$src" "${icon#/}"
		icon="$t/${icon#/}"
	fi
	[ -f "$icon" ] || icon=
	if [ -z "$icon" ] && [ "$m_iconname" ]; then
		img_extract "$src" "*$m_iconname*.png"
		img_extract "$src" "*$m_iconname*.svg"
	fi
	m_icon=$(pick_icon "$t")

	case "$(dd if="$src" bs=1 skip=4 count=1 2>/dev/null | \
		od -An -tx1 | tr -d ' \n')" in
		01) m_class="32-bit" ;;
		02) m_class="64-bit" ;;
		*)  m_class="unknown" ;;
	esac
	[ "$m_version" ] || m_version=$(guess_ver "$src")
	return 0
}

# Menu entry from the image's one: Exec and TryExec point to the installed
# file, Icon is our own name (the image's icon basename is not unique).
# DBusActivatable would ask for a service file we don't ship. Without FUSE
# the runtime must extract the image before running it: the flag goes
# right after the image, before the application arguments.
rewrite_desktop() {
	local src="$1" dst="$2" exec runflag=
	exec=$(deskval Exec "$src")
	have_fuse || runflag=' --appimage-extract-and-run'
	# Replace the launcher token and keep the arguments (%U, %F,
	# --no-sandbox, env FOO=bar ...).
	case " $exec " in
		*" AppRun "*)
			exec=$(printf ' %s ' "$exec" | \
				sed "s| AppRun |$(sedsafe "$appimage$runflag") |")
			exec=${exec# }
			exec=${exec% } ;;
	esac
	[ "$exec" ] || exec="$appimage$runflag"

	sed -e "s|^Exec=.*|Exec=$(sedsafe "$exec")|" \
		-e "s|^TryExec=.*|TryExec=$(sedsafe "$appimage")|" \
		-e "s|^Icon=.*|Icon=$(sedsafe "$slug")|" \
		-e "/^DBusActivatable=/d" \
		"$src" > "$dst" || return 1

	# No Exec in the image's entry: add ours in the Desktop Entry group.
	if ! grep -q '^Exec=' "$dst"; then
		awk -v e="Exec=$appimage" \
			'/^\[Desktop Entry\]$/ { print; print e; next } { print }' \
			"$dst" > "$dst.new" && mv "$dst.new" "$dst"
	fi
	return 0
}

# Show one image before install: no file is written outside the temporary
# directory.
info_file() {
	local src="$1" file sum state slug
	file="$src"
	src=$(abs_path "$src")
	check_image "$src" || exit 1
	tmpinit
	work_image "$src"

	if ! meta_read "$wimg"; then
		gettext "Cannot read the image (no .desktop file inside):"; echo " $file"
		exit 1
	fi

	sum=$(sha256sum "$wimg" 2>/dev/null | cut -d' ' -f1)
	slug=$(slugify "${name:-${m_name:-$m_deskid}}")
	state=$(gettext "not installed")
	[ -f "$dbdir/$slug.info" ] && state=$(gettext "installed")

	newline
	boldify "Spk-appimage info"
	separator
	printf '%-13s %s\n' "$(gettext 'Name:')" "$m_name"
	printf '%-13s %s\n' "$(gettext 'Version:')" "${m_version:--}"
	printf '%-13s %s (%s)\n' "$(gettext 'Architecture:')" \
		"$(uname -m)" "ELF $m_class"
	printf '%-13s %s (%s)\n' "$(gettext 'File:')" \
		"$(basename "$file")" "$(hsize "$wimg")"
	printf '%-13s %s\n' "$(gettext 'SHA256:')" "${sum:--}"
	printf '%-13s %s\n' "$(gettext 'Categories:')" "${m_cats:--}"
	printf '%-13s %s\n' "$(gettext 'Exec:')" "${m_exec:--}"
	if [ "$m_icon" ]; then
		printf '%-13s %s\n' "$(gettext 'Icon:')" \
			"${m_icon##*/} ($(printf '%s' "$m_icon" | \
			sed -n 's|.*/\([0-9]*x[0-9]*\)/.*|\1|p'))"
	fi
	printf '%-13s %s\n' "$(gettext 'Install name:')" "$slug"
	printf '%-13s %s\n' "$(gettext 'Install path:')" \
		"$appsdir/$slug.AppImage"
	if have_fuse; then
		printf '%-13s %s\n' "$(gettext 'Run mode:')" "fuse"
	else
		printf '%-13s %s\n' "$(gettext 'Run mode:')" \
			"extract-and-run (no /dev/fuse)"
	fi
	printf '%-13s %s\n' "$(gettext 'Status:')" "$state"
	separator
	newline
}

# Show an installed AppImage from its .info file.
info_installed() {
	local f="$dbdir/$1.info"
	(
		unset NAME DISPLAY_NAME VERSION CATEGORIES APPIMAGE DESKTOP ICON \
			SIZE SHA256 SOURCE MODE DATE
		. "$f"
		newline
		boldify "Spk-appimage info"
		separator
		printf '%-13s %s\n' "$(gettext 'Name:')" "${DISPLAY_NAME:--}"
		printf '%-13s %s\n' "$(gettext 'Version:')" "${VERSION:--}"
		printf '%-13s %s\n' "$(gettext 'File:')" \
			"$APPIMAGE ($(hsize "$APPIMAGE"))"
		printf '%-13s %s\n' "$(gettext 'SHA256:')" "${SHA256:--}"
		printf '%-13s %s\n' "$(gettext 'Categories:')" "${CATEGORIES:--}"
		printf '%-13s %s\n' "$(gettext 'Command:')" "$bindir/$NAME"
		printf '%-13s %s\n' "$(gettext 'Menu entry:')" "${DESKTOP:--}"
		printf '%-13s %s\n' "$(gettext 'Icon:')" "${ICON:--}"
		printf '%-13s %s\n' "$(gettext 'Run mode:')" "$MODE"
		printf '%-13s %s\n' "$(gettext 'Source:')" "${SOURCE:--}"
		printf '%-13s %s\n' "$(gettext 'Installed:')" "${DATE:--}"
		separator
		newline
	)
}

info_one() {
	local arg="$1" dl
	[ "$arg" ] || usage
	case "$arg" in
		http://*|https://*|ftp://*)
			tmpinit
			dl="$tmpdir/${arg##*/}"
			gettext "Downloading:"; echo " $arg"
			wget --no-check-certificate -q -O "$dl" "$arg" || {
				gettext "Cannot download:"; echo " $arg"; exit 1; }
			info_file "$dl"
			return ;;
	esac
	if [ -f "$dbdir/$(basename "${arg%.AppImage}").info" ] && [ ! -e "$arg" ]
	then
		info_installed "$(basename "${arg%.AppImage}")"
	else
		info_file "$arg"
	fi
}

# Install one image: binary, command, menu entry, icon and .info file.
install_one() {
	local src="$1" file urldl= icon ext iconsize sum size
	[ "$src" ] || usage

	tmpinit
	case "$src" in
		http://*|https://*|ftp://*)
			file="${src##*/}"
			urldl="$src"
			gettext "Downloading:"; echo " $src"
			wget --no-check-certificate -q -O "$tmpdir/$file" "$src" || {
				gettext "Cannot download:"; echo " $src"; exit 1; }
			src="$tmpdir/$file" ;;
	esac
	src=$(abs_path "$src")
	file=$(basename "$src")
	check_image "$src" || exit 1
	work_image "$src"

	if ! meta_read "$wimg"; then
		gettext "Cannot read the image (no .desktop file inside):"; echo " $file"
		exit 1
	fi

	# Install name: the application name (Signal, OpenCode), else the
	# desktop entry id, --name wins over both.
	slug=$(slugify "${name:-${m_name:-$m_deskid}}")
	[ "$slug" ] || die "Invalid install name: %s" "${name:-$m_deskid}"

	if [ -f "$dbdir/$slug.info" ] && [ -z "$force" ]; then
		gettext "Already installed:"; echo " $slug"
		gettext "Use --force to replace it."; newline
		exit 1
	fi

	appimage="$appsdir/$slug.AppImage"
	desktop="$menudir/$slug.desktop"
	[ "$no_desktop" ] && desktop=
	icon=

	gettext "Installing:"; echo " $slug"
	separator
	mkdir -p "$appsdir" "$bindir" "$menudir" "$dbdir" || exit 1

	# Never overwrite a real file of the user with our command link.
	if [ -e "$bindir/$slug" ] && [ ! -L "$bindir/$slug" ] && \
		[ -z "$force" ]; then
		gettext "A file already exists:"; echo " $bindir/$slug"
		gettext "Use --force to replace it."; newline
		exit 1
	fi

	gettext "Copying the AppImage..."
	if [ "$wimg" != "$appimage" ]; then
		cp -f "$wimg" "$appimage" || { status; exit 1; }
	fi
	chmod 755 "$appimage"
	ln -sfn "$appimage" "$bindir/$slug"
	status

	if [ -z "$no_desktop" ]; then
		gettext "Creating the menu entry..."
		rewrite_desktop "$m_desktop" "$desktop" || { status; exit 1; }
		status
	fi

	if [ "$m_icon" ]; then
		gettext "Installing the icon..."
		ext=${m_icon##*.}
		case "$m_icon" in
			*/scalable/*) iconsize=scalable ;;
			*)
				iconsize=$(printf '%s' "$m_icon" | \
					sed -n 's|.*/\([0-9][0-9]*x[0-9][0-9]*\)/.*|\1|p')
				[ "$iconsize" ] || iconsize=256x256 ;;
		esac
		mkdir -p "$icondir/$iconsize/apps"
		icon="$icondir/$iconsize/apps/$slug.$ext"
		cp -f "$m_icon" "$icon" || { status; exit 1; }
		status
	fi

	sum=$(sha256sum "$appimage" 2>/dev/null | cut -d' ' -f1)
	size=$(wc -c < "$appimage" | tr -d ' ')
	if have_fuse; then mode=fuse; else mode=extract-and-run; fi

	{
		echo "# spk-appimage: installed AppImage metadata"
		printf 'NAME="%s"\n' "$(esc "$slug")"
		printf 'DISPLAY_NAME="%s"\n' "$(esc "$m_name")"
		printf 'VERSION="%s"\n' "$(esc "$m_version")"
		printf 'CATEGORIES="%s"\n' "$(esc "$m_cats")"
		printf 'APPIMAGE="%s"\n' "$(esc "$appimage")"
		printf 'DESKTOP="%s"\n' "$(esc "$desktop")"
		printf 'ICON="%s"\n' "$(esc "$icon")"
		printf 'SIZE="%s"\n' "$size"
		printf 'SHA256="%s"\n' "$sum"
		printf 'SOURCE="%s"\n' "$(esc "${urldl:-$src}")"
		printf 'MODE="%s"\n' "$mode"
		printf 'DATE="%s"\n' "$(date '+%Y-%m-%d %H:%M')"
	} > "$dbdir/$slug.info" || exit 1

	separator
	printf '%-13s %s\n' "$(gettext 'AppImage:')" \
		"$appimage ($(hsize "$appimage"))"
	printf '%-13s %s\n' "$(gettext 'Command:')" "$bindir/$slug"
	[ -z "$no_desktop" ] && \
		printf '%-13s %s\n' "$(gettext 'Menu entry:')" "$desktop"
	[ "$icon" ] && printf '%-13s %s\n' "$(gettext 'Icon:')" "$icon"
	printf '%-13s %s\n' "$(gettext 'Run mode:')" "$mode"
	if [ "$mode" != fuse ]; then
		gettext "No /dev/fuse: the image is extracted to /tmp on every start."
		newline
	fi
	separator
	case ":$PATH:" in
		*":$bindir:"*) ;;
		*) gettext "Note: ~/.local/bin is not in this PATH (new shells get it from /etc/profile)."
			newline ;;
	esac
	newline
}

# Remove one installed AppImage. Nothing is deleted outside our paths and
# the user data (~/.config) is left alone.
remove_one() {
	local slug f
	slug=$(basename "${1%.AppImage}")
	case "$slug" in
		""|*[!a-z0-9._-]*)
			die "Invalid AppImage name: %s" "$1" ;;
	esac
	if [ ! -f "$dbdir/$slug.info" ]; then
		gettext "Not installed:"; echo " $slug"
		exit 1
	fi
	unset NAME DISPLAY_NAME APPIMAGE DESKTOP ICON
	. "$dbdir/$slug.info"
	case "${NAME:-}" in
		""|*[!a-z0-9._-]*) NAME="$slug" ;;
	esac

	gettext "Removing:"; echo " $NAME"
	separator
	for f in "$APPIMAGE" "$DESKTOP" "$ICON" "$bindir/$NAME"; do
		case "$f" in
			"$appsdir"/*|"$datadir"/*|"$bindir"/*) ;;
			*) continue ;;
		esac
		# -L: the command link is dangling once the AppImage is gone.
		{ [ -e "$f" ] || [ -L "$f" ]; } && rm -f "$f"
	done
	rm -f "$dbdir/$slug.info"
	gettext "Removed."; newline
}

# List installed AppImages: human columns, --raw TSV or --trame JSON.
list_all() {
	local f n=0
	set -- "$dbdir"/*.info
	if [ ! -f "$1" ]; then
		gettext "No AppImage installed."; newline
		exit 0
	fi

	if [ "$raw" ]; then
		for f in "$@"; do
			( unset NAME VERSION SIZE MODE APPIMAGE; . "$f"
				printf '%s\t%s\t%s\t%s\t%s\n' \
					"$NAME" "$VERSION" "$SIZE" "$MODE" "$APPIMAGE" )
		done
		exit 0
	fi

	if [ "$trame" ]; then
		printf '{"command":"appimage list","results":['
		for f in "$@"; do
			[ "$n" = 0 ] || printf ','
			n=1
			( unset NAME VERSION SIZE MODE APPIMAGE; . "$f"
				printf '{"name":"%s","version":"%s","size":%s,' \
					"$(json_esc "$NAME")" "$(json_esc "$VERSION")" \
					"${SIZE:-0}"
				printf '"run_mode":"%s","path":"%s"}' \
					"$(json_esc "$MODE")" "$(json_esc "$APPIMAGE")" )
		done
		printf ']}\n'
		exit 0
	fi

	newline
	boldify "Spk-appimage list"
	separator
	printf '%-22s %-10s %-8s %s\n' "NAME" "VERSION" "SIZE" "RUN"
	for f in "$@"; do
		( unset NAME VERSION SIZE MODE APPIMAGE; . "$f"
			case "$MODE" in
				extract-and-run) mode=extract ;;
				*) mode="$MODE" ;;
			esac
			printf '%-22s %-10s %-8s %s\n' \
				"$NAME" "${VERSION:--}" "$(hsize "$APPIMAGE")" \
				"$mode" )
	done
	separator
	newline
}

# Run an installed AppImage, falling back to extraction when FUSE is not
# available (the module may have been unloaded since the install).
run_one() {
	local slug="$1"
	[ "$slug" ] || usage
	[ -f "$dbdir/$slug.info" ] || die "Not installed: %s" "$slug"
	unset APPIMAGE MODE
	. "$dbdir/$slug.info"
	shift
	if have_fuse; then
		exec "$APPIMAGE" "$@"
	fi
	exec "$APPIMAGE" --appimage-extract-and-run "$@"
}

#
# Commands and exit
#

case "$1" in
	""|-h|--help|usage|help) usage ;;
	info)    shift; info_one "$1" ;;
	install) shift; install_one "$1" ;;
	remove|rm) shift
		[ "$1" ] || usage
		for arg in "$@"; do remove_one "$arg"; done ;;
	list|ls) list_all ;;
	run) shift; run_one "$@" ;;
	*) die "Unknown command: %s" "$1" ;;
esac

exit 0
