#!/bin/bash
ACTION="$1"
shift
PACKAGE_LIST=$@

# START Define variables
# END Define Variables

# simplayer
# simplayer-phet-activitiestype
# simplayer-circuit
# simplayer-flash-activities
# simplayer-myphysicslab-activities
# kgeography
# kbruch
# kig
# kalgebra
# cantor
# octave
# kalzium
# kmplot
# rocs
# step

status() {
    ret=$(dpkg-query -W -f '${Status}' "$@" 2>/dev/null)
}
if [ -n "$ACTION" -a "$ACTION" != "getStatus" ]; then
    echo "ACTION=${ACTION} PACKAGE_LIST=${PACKAGE_LIST}"
fi
case $ACTION in
    getStatus)
        # Warning: Nothing MUST be echoed in the script before this point
        # Type apt MUST echo ONLY "Not found", otherwise "0" (installed) "1" (not-installed) for other types not "apt"
        echo "Not found"
    ;;

    download)
        echo "download phase ..."
    ;;

    preInstall)
        echo "preInstall phase ..."
    ;;

    installPackage)
        # ommited for "apt" type
        echo "installPackage phase ..."
    ;;

    postInstall)
        echo "postInstall phase ..."
        for pkg in ${PACKAGE_LIST}; do
            if [ "${pkg}" == "cantor" ];then
                additional="cantor-backend-kalgebra cantor-backend-octave cantor-backend-python"
                for item in $additional; do
                    status $item
                    if [ "${ret}" != "install ok installed" ]; then
                        apt-get install -y $item
                        echo "INSTALLED $item"
                    fi
                done
                status "cantor-backend-qalculate"
                if [ "${ret}" == "install ok installed" ]; then
                    apt-get remove -y cantor-backend-qalculate
                fi
            fi
        done
    ;;

    remove)
        echo "remove phase ..."
        for pkg in ${PACKAGE_LIST}; do
            if [ "${pkg}" == "cantor" ]; then
                additional="cantor-backend-kalgebra cantor-backend-octave cantor-backend-python cantor"
                for item in $additional; do
                    status $item
                    if [ "${ret}" == "install ok installed" ]; then
                        apt-get remove -y $item
                        echo "REMOVED $item"
                    fi
                done
            else
                apt-get remove -y $pkg
            fi
        done
    ;;
esac
exit 0
