#!/bin/sh

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

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="$(/usr/sbin/appsupport-config --instance $2 --name)"
    shift
    shift
elif [ "$1" == "--help" ]; then
    exec lxc-$CMD --help
    exit 0
fi

if [ -z "$INSTANCE_NAME" ]; then
    INSTANCE_NAME="$(/usr/sbin/appsupport-config --name)"
fi

case $CMD in
    info)
        case $1 in
            --running)
                if [ -n "$(lxc-info -n $INSTANCE_NAME --lxcpath=$LXC_CONFIG_PATH --state | grep RUNNING)" ]; then
                    exit 0
                fi
                exit 1
                ;;
        esac
        ;;
    attach)
        CMD_DELIM="--"
        ;;
esac

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