#!/bin/bash

if [ "$*" = "" ]
then
    echo "usage: $0 [appimage-file [arguments ...]]"
    echo "    This is helper script to run appimages for additional-base-lib."
    echo
    echo "    You have to ensure input file IS an appimage, for this script"
    echo "    does not check. If you input other files, It will become"
    echo "    unpredictable."
    echo
    echo "    There is a more convenient script to handle both normal executable"
    echo "    and appimage, called ablrun."
    echo "    usage: ablrun [command [arguments ...]]"
    exit
fi

ABLIMAGE_PARAMETERS=("$@")

coproc "$1" --appimage-mount

ABLIMAGE_PID=$!

cleanup() {
    kill $ABLIMAGE_PID
    exit
}
trap cleanup SIGHUP
trap cleanup SIGINT
trap cleanup SIGTERM

if [ ! -e /proc/$! ]
then
    echo "Child process failed."
    exit 1
fi

read -u ${COPROC[0]} ABLIMAGE_DIR

ablrun-normal "$ABLIMAGE_DIR/AppRun" ${ABLIMAGE_PARAMETERS[@]:1}

cleanup
