#!@l_prefix@/bin/bash
##
##  openpkg-docker.sh -- OpenPKG Docker shell
##

#   OpenPKG instance configuration
prefix="@l_prefix@"

#   allow images to hook command into this entrypoint shell
if [ -f "$prefix/etc/openpkg-docker/local.sh" ]; then
    source "$prefix/etc/openpkg-docker/local.sh"
fi

#   the default commands
cmd_start () {
    echo "++ starting OpenPKG service(s)"
    $prefix/bin/openpkg rc all start
}
cmd_stop () {
    echo "++ stopping OpenPKG service(s)"
    $prefix/bin/openpkg rc all stop
}
cmd_shell () {
    echo "++ entering GNU Bash shell"
    $prefix/bin/bash "$@"
    echo "++ leaving GNU Bash shell"
}
cmd_help () {
    echo "++ available OpenPKG Docker shell commands:"
    echo "-- help ............ display this help message"
    echo "-- quit ............ quit from this shell"
    echo "-- start ........... start all OpenPKG services"
    echo "-- stop ............ stop  all OpenPKG services"
    echo "-- shell ........... enter GNU Bash shell"
}
cmd_quit () {
    echo "** leaving OpenPKG Docker shell"
    exit 0
}

#   dispatch a particular command (with optional arguments)
dispatch () {
    name="$1"
    shift
    if [ ".$(type -t cmd_${name})" = .function ]; then
        if [ ".$(type -t cmd_${name}_before)" = .function ]; then
            eval "cmd_${name}_before" "$@"
        fi
        eval "cmd_${name}" "$@"
        if [ $? -eq 0 ]; then
            if [ ".$(type -t cmd_${name}_after)" = .function ]; then
                eval "cmd_${name}_after" "$@"
            fi
        fi
    else
        echo "** ERROR: invalid command \"$name\""
    fi
}

#   gracefully shutdown on catched signals
trap 'if [ $auto = yes ]; then dispatch "stop"; fi; dispatch "quit"' HUP INT QUIT TERM

#   support suppression of automatic start/stop commands
auto=yes
if [ ".$1" = ".--no-auto" ]; then
    shift
    auto=no
fi

#   dispatch processing according to usage pattern
if [ $# -ge 1 ]; then
    #   one-time command
    cmd="$1"
    shift
    dispatch "$cmd" "$@"
elif tty -s; then
    #   interative session
    echo "** entering OpenPKG Docker shell (interactive session, pid: $BASHPID)"
    if [ $auto = yes ]; then
        dispatch "start"
    fi
    dispatch "help"
    while true; do
        read -e -p ">> " -a cmd
        if [ $? -ne 0 ]; then
            echo "quit"
            if [ $auto = yes ]; then
                dispatch "stop"
            fi
            cmd=("quit")
        elif [ ".${cmd[*]}" = .quit ]; then
            if [ $auto = yes ]; then
                dispatch "stop"
            fi
        elif [ ".${cmd[*]}" = . ]; then
            continue
        fi
        dispatch "${cmd[@]}"
    done
else
    #   non-interactive service loop
    if [ $auto = yes ]; then
        dispatch "start"
    fi
    while true; do
        sleep 600
    done
fi

