#! /bin/bash

# Export APPRUN if running from an extracted image
self="$(readlink -f -- $0)"
here="${self%/*}"
APPDIR="${APPDIR:-${here}}"
FEATURE_FLAGS="${FEATURE_FLAGS}"

# Export SSL certificate
export SSL_CERT_FILE="${APPDIR}/opt/_internal/certs.pem"

if [ "$1" == "service" ]; then
    exec /bin/bash "${APPDIR}/install-infection-monkey-service.sh" ${@:2}
fi

# Check if running as root
if [ "$EUID" -eq 0 ]; then
    echo "AppImage: Warning: running as root is not recommended. You should instead run the AppImage as a regular user."
    echo "AppImage: If you want to run the Agent as root, do so by choosing manual run mode."
fi

# Call the entry point
for opt in "$@"; do
    [ "${opt:0:1}" != "-" ] && break
    if [[ "${opt}" =~ "I" ]] || [[ "${opt}" =~ "E" ]]; then
        # Environment variables are disabled ($PYTHONHOME). Let's run in a safe
        # mode from the raw Python binary inside the AppImage
        "$APPDIR/opt/python3.11/bin/python3.11" "$@"
        exit "$?"
    fi
done


export PYTHONNOUSERSITE=1

run_island="${APPDIR}/opt/python3.11/bin/python3.11 ${APPDIR}/usr/src/monkey_island.py"

if [[ -z ${MONKEY_APPIMAGE_SERVICE_RUN+x} ]]; then
    # Save HOME and USER because capsh changes them. Until ubuntu adds --noenv option we have to rely on a workaround
    home_original=$HOME
    user_original=$USER

    (PYTHONHOME="${APPDIR}/opt/python3.11" sudo capsh --keep=1 --user=${user_original} --inh=cap_net_bind_service --addamb=cap_net_bind_service -- -c "env HOME=${home_original} USER=${user_original} FEATURE_FLAGS=${FEATURE_FLAGS} ${run_island}" "$@")
else
    (PYTHONHOME="${APPDIR}/opt/python3.11" ${run_island})
fi

exit "$?"
