#!/bin/sh

# Copyright (c) 2022 - 2023 Jolla Ltd.
#
# License: Jolla Proprietary

LXC_CONFIG_PATH="$(/usr/sbin/appsupport-config --lxc-path)"
INSTANCE_NAME=
CMD_DELIM=
CMD=${0##*-}
CHECK_RUNNING=0
APPSUPPORT_FAIL=0
VARS=

if [ -z "$CMD" ]; then
    CMD=attach
fi

# appsupport-info only accepts --instance as -i is valid argument for the command.
# appsupport-attach can use both --instance and short argument -i.
if [ "$1" = "--instance" ] || { [ "$1" = "-i" ] && [ "$CMD" != "info" ] ;}; then
    if [ -z "$2" ]; then
        echo "$1 requires argument."
        exit 1
    fi
    INSTANCE_NAME="$2"
    shift
    shift
elif [ "$1" = "--help" ]; then
    exec lxc-$CMD --help
    exit 0
elif [ "$1" = "--version" ]; then
    exec /usr/sbin/appsupport-config --version
fi

print_err() {
    >&2 echo "$@"
}

print_log() {
    if [ $CHECK_RUNNING -eq 0 ]; then
        print_err "$@"
    fi
}

detect_instance_name() {
    if [ -z "$INSTANCE_NAME" ]; then
        if [ $CHECK_RUNNING -eq 1 ]; then
            print_err "Instance name needed."
            exit 1
        fi

        RUNNING_COUNT="$(lxc-ls --lxcpath=$LXC_CONFIG_PATH --line --running | wc -l)"
        if [ $RUNNING_COUNT -eq 0 ]; then
            print_log "No AppSupport instances running."
            exit 1
        elif [ $RUNNING_COUNT -gt 1 ]; then
            print_log "Multiple AppSupport instances running:"
            for NAME in $(lxc-ls --lxcpath=$LXC_CONFIG_PATH --line --running); do
                print_log "  $NAME"
            done
            exit 1
        fi

        INSTANCE_NAME="$(lxc-ls --lxcpath=$LXC_CONFIG_PATH --line --running | head -n1)"
    fi
}

appsupport_running() {
    INSTANCE_STATE="$(lxc-info -n $INSTANCE_NAME --lxcpath=$LXC_CONFIG_PATH --state 2>&1)"

    if [ $? -ne 0 ]; then
        # Fallback if user requesting lxc-info doesn't have enough access rights
        ps a | grep "lxc-start" | grep -- "-n $INSTANCE_NAME" 2>&1 1>/dev/null
        if [ $? -eq 0 ]; then
            print_log "$INSTANCE_STATE"
            APPSUPPORT_FAIL=1
            return 0
        fi
    fi

    if [ -z "$(echo "$INSTANCE_STATE" | grep RUNNING)" ]; then
        print_log "AppSupport instance '$INSTANCE_NAME' is not running."
        return 1
    fi

    return 0
}

case $CMD in
    info)
        case $1 in
            --running)
                CHECK_RUNNING=1
                detect_instance_name
                appsupport_running
                exit $?
                ;;
        esac
        detect_instance_name
        ;;
    attach)
        detect_instance_name
        if ! appsupport_running || [ $APPSUPPORT_FAIL -eq 1 ]; then
            exit 1
        fi
        ROOTFS_PATH="$(/usr/sbin/appsupport-config --rootfs)"
        VARS="--clear-env $(grep export $ROOTFS_PATH/init.environ.rc | sed 's/.*export \(.*\) \(.*\)/--set-var \1=\2 /')"
        CMD_DELIM="--"
        ;;
esac

exec lxc-$CMD -l CRIT $VARS -n $INSTANCE_NAME --lxcpath=$LXC_CONFIG_PATH $CMD_DELIM "$@"
