#!/bin/sh
# apkd-install: Helper script to install/uninstall and handle .apk files
#
# Copyright (c) 2013 - 2022 Jolla Ltd.
#
# License: Jolla Proprietary

DBUS_SERVICE_NAME=com.jolla.apkd
DBUS_OBJECT_PATH=/com/jolla/apkd
DBUS_INTERFACE=com.jolla.apkd
INSTANCE=
COUNT=0

CMD=$(basename "$0")

if [ "$CMD" = "apkd-uninstall" ]; then
    DBUS_METHOD=removePackage
elif [ "$CMD" = "apkd-install-preload" ]; then
    DBUS_METHOD=installPreloadFile
elif [ "$CMD" = "apkd-install" ]; then
    DBUS_METHOD=installFile
else # apkd-harbour-rpm-preun and apkd-harbour-rpm-post - no-op, let the dir watcher handle it
    exit 0
fi

while [ $# -gt 0 ]; do
    case "$1" in
        -i|--instance)
            shift
            INSTANCE="$1"
        ;;
        *)
            eval "FILE_$COUNT=\$1"
            COUNT=$((COUNT + 1))
        ;;
    esac
    shift
done

if [ -z "$INSTANCE" ]; then
    WHO=$(whoami)
    # Try to detect instance from currently active user and running instance
    if [ "$WHO" != "root" ] && /usr/sbin/appsupport-service -q is-active $WHO; then
        INSTANCE=$WHO
    fi
fi

if [ $COUNT -eq 0 ] || [ -z "$INSTANCE" ]; then
    if [ "$CMD" = "apkd-uninstall" ]; then
        >&2 echo "Usage: $CMD -i <instance name> <package.to.remove>"
    else
        >&2 echo "Usage: $CMD -i <instance name> <package.apk> [<split_part2.apk> ...]"
    fi
    exit 1
fi

BUS="--session"
if [ "$(appsupport-config --instance "$INSTANCE" --value DBusAlwaysUseSystemBus)" = "true" ]; then
    BUS="--system"
fi


if [ "$DBUS_METHOD" = "installFile" ] && [ $COUNT -ge 2 ]; then
    DBUS_METHOD="installSplitFile"

    FILES_ABS=
    NUM=0
    while [ $NUM -lt $COUNT ]; do
        eval "FILEVAR=\$FILE_$NUM"
        FILENAME=${FILEVAR}
        NUM=$((NUM + 1))

        # Make sure we always pass an absolute file path
        ABS_FILENAME="$(readlink -f "$FILENAME")"
        if [ -z "$FILES_ABS" ]; then
            FILES_ABS="$ABS_FILENAME"
        else
            FILES_ABS=$FILES_ABS",$ABS_FILENAME"
        fi
    done

    dbus-send $BUS --print-reply \
        --dest=$DBUS_SERVICE_NAME \
        $DBUS_OBJECT_PATH \
        ${DBUS_INTERFACE}.${DBUS_METHOD} \
        "array:string:$FILES_ABS" \
        boolean:true
else
    NUM=0
    while [ $NUM -lt $COUNT ]; do
        eval "FILEVAR=\$FILE_$NUM"
        FILENAME=${FILEVAR}
        NUM=$((NUM + 1))

        if [ "$CMD" != "apkd-uninstall" ]; then
            # Make sure we always pass an absolute file path
            FILENAME="$(readlink -f "$FILENAME")"
        fi

        # Pass full file path to apkd via d-bus
        dbus-send $BUS --print-reply \
            --dest=$DBUS_SERVICE_NAME \
            $DBUS_OBJECT_PATH \
            ${DBUS_INTERFACE}.${DBUS_METHOD} \
            "string:$FILENAME"
    done
fi

