#!/bin/bash
# barium helper scripts
# author: rosalinux.ru: betcher_
echo "Warning. Alpha version of utility"

if [ -f $(dirname $0)/lib ] ;  then
    . $(dirname $0)/lib
else 
    . $(which lib) || exit 1
fi

while [ -n "$1" ] ; do
		case $1 in
			'-h' | '--help' ) HELP ;;
			'-o' | '--name' ) shift ; NAME="$1" ;;
			'-a' | '--appimage' ) shift ; APPIMG="$1" ;;
			'-'*) 	echo "$(basename "$0"): invalid option ${1}"
				exit ${LINENO} ;;
			*) 	[ $APPIMG ] || APPIMG="$1";;
		esac
		shift
	done

if [ "$APPIMG" ] ; then 
	APPIMG=$(realpath $APPIMG)
	[ -f "$APPIMG" ] || echo_exit "No such file: $APPIMG" ${LINENO}
	[ -x "$APPIMG" ] || chmod +x "$APPIMG"
else
	echo_exit "Please specify appimage file" ${LINENO}
fi 

[ "$NAME" ] || NAME="$(basename $APPIMG)"
NAME="${NAME%.*}"
TMPD=$(mktemp -d /tmp/appimg2mod-XXX)
XZM=${TMPD}/img.xzm
MPOINT="${TMPD}/MPOINT"
ROOT="${TMPD}/${NAME}"
BASE="${ROOT}/opt/appimages/$NAME"
mkdir -p "$BASE" "${ROOT}/usr/bin" "${ROOT}/usr/share/applications" "${ROOT}/usr/share/icons" "$MPOINT"

OFFSET=$($APPIMG --appimage-offset)
dd if=$APPIMG of=$XZM skip=$OFFSET ibs=1
mount -o loop "$XZM" "$MPOINT"
pushd $MPOINT
	cp *.{png,svg} "${ROOT}/usr/share/icons/" 2>/dev/null
	[ "$(ls -1 *.desktop | wc -l)" -gt 1 ] && echo "Warning! More than one desktop files" 
	for a in $(ls -1 *.desktop ) ; do 
		cp $a "${ROOT}/usr/share/applications/"
		desktops="$desktops $a"
	done

	cp -fax ./* ${BASE}/
	if [ -L ./AppRun ] ; then
		bin_name=$(basename $(readlink ./AppRun)) 
		ln -s "/opt/appimages/$NAME/AppRun" "${ROOT}/usr/bin/$bin_name"
	else
		bin_name=$(cat *.desktop | grep -m 1 -i 'exec=' | sed 's/[Ee]xec=//' |cut -f1 -d ' ' )
		cat <<EOF > "${ROOT}/usr/bin/$bin_name"
#!/bin/sh
cd /opt/appimages/$NAME
exec ./AppRun
EOF
		chmod +x "${ROOT}/usr/bin/$bin_name"
	fi
popd

umount $MPOINT
mksquashfs $ROOT ${NAME}.xzm $SQFSOPT -noappend
rm -rf $TMPD
echo "Executable:    /usr/bin/$bin_name"
echo "Desktop file(s): $desktops"
