#!/bin/bash

#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# script based on https://github.com/coreos/toolbox/

set -eo pipefail

# Defaults
REGISTRY=registry.opensuse.org
IMAGE=opensuse/toolbox
TOOLBOX_NAME=toolbox-"${USER}"
TOOLBOXRC="${HOME}"/.toolboxrc
TOOLBOX_SHELL="/bin/bash"
SUDO=

if command -v podman &> /dev/null ; then
    CLI=podman
elif command -v docker &> /dev/null ; then
    CLI=docker
else
    echo "$0: ERROR: neither 'podman' nor 'docker' are available. Exiting!"
fi

test -f /usr/etc/toolboxrc && . /usr/etc/toolboxrc
test -f /etc/toolboxrc && . /etc/toolboxrc

MODE="system"

setup() {
    # Allow user overrides
    if [ -f "${TOOLBOXRC}" ]; then
        echo ".toolboxrc file detected, overriding defaults..."
        source "${TOOLBOXRC}"
    fi
    TOOLBOX_IMAGE="${REGISTRY}"/"${IMAGE}"
}

create() {
    local msg="create"
    if ! container_exists; then
        if ! image_exists || [ -z "$NO_PULL" ]; then
            image_pull
        fi
        local runlabel
        runlabel=$(image_runlabel) ||:

        echo "Spawning a container '$TOOLBOX_NAME' with image '$TOOLBOX_IMAGE'"
        if [[ -z "$runlabel" ]]; then
            container_create
        else
            echo "Detected RUN label in the container image. Using that as the default..."
            container_runlabel
            return
        fi
        # We want to do the user setup only when the container is created for the first time
        [[ -n "${CREATE_AS_USER}" ]] && SETUP_USER=true
    else
        echo "Container '$TOOLBOX_NAME' already exists. Trying to start..."
        echo "(To remove the container and start with a fresh toolbox, run: $CLI rm '$TOOLBOX_NAME')"
        msg="start"
    fi

    local state
    state=$(container_state)
    if [[ "$state" == configured ]] || [[ "$state" == exited ]] || [[ "$state" == stopped ]] || [[ "$state" == created ]]; then
        container_start
    elif [[ "$state" != running ]]; then
        echo "Container '$TOOLBOX_NAME' in unknown state: '$state'"
        return 1
    fi

    if [[ "${SETUP_USER}" = "true" ]]; then
        echo "Setting up user '${USER_NAME}' (with 'sudo' access) inside the container..."
        echo "(NOTE that, if 'sudo' and related packages are not present in the image already,"
        echo "this may take some time. But this will only happen now that the toolbox is being created)"
        local tmp_user_setup
        tmp_user_setup=$(mktemp "${HOME}/.${TOOLBOX_NAME}-user-setup-XXXXXX.sh")
        tmp_user_setup_log="/dev/null"
        # DEBUG: uncomment the following line to see logs of the script in /tmp
        #tmp_user_setup_log="/tmp/$(basename -- ${tmp_user_setup}).log"
        cat <<EOF > "${tmp_user_setup}"
#!/bin/bash
groupadd -g ${USER_GID} ${USER_GNAME}
useradd -M -N -g ${USER_GNAME} -u ${USER_ID} ${USER_NAME}
if ! command -v sudo &> /dev/null ; then
  if command -v zypper &> /dev/null ; then
    zypper install -y --no-recommends sudo
  elif command -v apt &> /dev/null ; then
    apt update && apt -y install sudo
  elif command -v dnf ; then
    dnf install -y sudo
  fi
fi
mkdir -p /etc/sudoers.d/ && echo "${USER_NAME} ALL = (root) NOPASSWD:ALL" > /etc/sudoers.d/${USER_NAME}
# Avoid issues when updating some packages
if [ -d "/usr/lib/rpm/macros.d/" ]; then
  # Problematic packages are (on openSUSE):
  # - filesystem: touches /dev
  # - netcfg: touches /etc/hosts
  echo "%_netsharedpath /dev/:/etc/hosts" > /usr/lib/rpm/macros.d/macros.microos-toolbox
fi
EOF
        ${SUDO} $CLI exec --user root "${TOOLBOX_NAME}" bash "${tmp_user_setup}" &> "${tmp_user_setup_log}"
        ${SUDO} $CLI exec --user root "${TOOLBOX_NAME}" rm "${tmp_user_setup}"
    fi

    echo "Container ${msg}ed."
}

run() {
    create

    echo "Entering container. To exit, type 'exit'."
    container_exec "$@"
}

cleanup() {
    active="$(container_active)"
    if [ $active != "" ] && [ $active -eq 0 ] && [ -z "$NO_STOP" ]; then
	${SUDO} $CLI stop "$TOOLBOX_NAME" &>/dev/null
    fi
}

container_exists() {
    ${SUDO} $CLI inspect "$TOOLBOX_NAME" &>/dev/null
}

container_state() {
    ${SUDO} $CLI inspect "$TOOLBOX_NAME" --format '{{.State.Status}}' 2> /dev/null
}

container_active() {
    ${SUDO} $CLI inspect "$TOOLBOX_NAME" --format '{{len .ExecIDs}}' 2> /dev/null
}

image_exists() {
    ${SUDO} $CLI inspect "$TOOLBOX_IMAGE" &>/dev/null
}

image_runlabel() {
    ${SUDO} $CLI container runlabel --display RUN "$TOOLBOX_IMAGE" 2> /dev/null
}

image_pull() {
    if [ -z ${SUDO} ] && [ $(id -u) -ne 0 ]; then
        if [ ! `grep $USER /etc/subuid` ] || [ ! `grep $USER /etc/subgid` ]; then
            echo "$0: ERROR: rootless mode wanted but no subuid and/or subgid for user '$USER'"
            echo " Toolbox will only work for this user if rootless $CLI is configured properly."
            echo " consider doing something like this:"
            echo "    sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 $USER"
            echo " and then restart."
            echo " Or use '-r', for using a rootfull container."
            exit 1
        fi
    fi
    ${SUDO} $CLI pull "$TOOLBOX_IMAGE"
}

list() {
    ${SUDO} $CLI ps --all
    exit $?
}

stop() {
    # We can't stop non-existing and non-running toolboxes
    if  ! container_exists ; then
        echo "$0: ERROR: Cannot stop non-existing container '$TOOLBOX_NAME'"
        exit 2
    fi
    if [[ "$(container_state)" != "running" ]]; then
        echo "$0: ERROR: Cannot stop non-running container '$TOOLBOX_NAME'"
        exit 2
    fi

    # We don't stop toolboxes with active sessions
    if [ $(container_active) -ne 0 ]; then
        echo "$0: ERROR: The toolbox '$TOOLBOX_NAME' has active sessions. Not stopping"
        exit 1
    fi

    ${SUDO} $CLI stop "$TOOLBOX_NAME" &> /dev/null
}

container_create() {
    if [ -z "$SANDBOX" ]; then
        # this is the default behavior, unless --sandbox is specified
        CREATE_NO_SANDBOX="--mount type=devpts,destination=/dev/pts,uid=$(id -u) --volume /sys:/sys:rslave --volume /:/media/root:rslave"
        CREATE_NO_SANDBOX="$CREATE_NO_SANDBOX --privileged --security-opt label=disable --pid host --ipc host"
    fi
    if ! ${SUDO} $CLI create \
                 $RUNTIME \
                 --hostname "$TOOLBOX_NAME" \
                 --name "$TOOLBOX_NAME" \
                 --network host \
                 ${CREATE_NO_SANDBOX} \
                 ${CREATE_AS_USER} \
                 --volume /etc/machine-id:/etc/machine-id:ro \
                 --volume /etc/localtime:/etc/localtime:ro \
                 "$TOOLBOX_IMAGE" sleep +Inf > /dev/null; then
        echo "$0: failed to create container '$TOOLBOX_NAME'"
        exit 1
    fi
}

container_start() {
    if ! ${SUDO} $CLI start "$TOOLBOX_NAME" > /dev/null ; then
        echo "$0: failed to start container '$TOOLBOX_NAME'"
        exit 1
    fi
}

container_runlabel() {
    if ! ${SUDO} $CLI container runlabel --name "$TOOLBOX_NAME" RUN "$TOOLBOX_IMAGE" > /dev/null ; then
        echo "$0: failed to runlabel on image '$TOOLBOX_IMAGE'"
        exit 1
    fi
}

container_exec() {
    ${SUDO} $CLI exec \
            --env LANG="$LANG" \
            --env TERM="$TERM" \
            --interactive \
            --tty "${EXEC_AS_USER[@]}" \
            "$TOOLBOX_NAME" \
            "$@"
}

show_help() {
    echo "USAGE: toolbox [[-h/--help] | [list|create [<name>]|enter [<name>]|run|stop [<name>]] [-r/--root] [-u/--user]
        [-n/--nostop] [-S/--sandbox] [-P/--no-pull] [[-R/--reg <registry>] [-I/--img <image>]|[-i/--image <image_URI>]]
        [-X/--runtime <runtime_bin>] [[-t/--tag <tag>]|[-c/--container <name>]] [command_to_run]]
toolbox is a small script that launches a container to let you bring in your favorite debugging or admin tools.
The toolbox container is a pet container and will be restarted on following runs.
To remove the container and start fresh, do $CLI rm ${TOOLBOX_NAME}.

Commands are optional and imply user mode (-u):
 list: List existing toolboxes
 create: Just create the toolbox
 enter: Enter inside a toolbox (if it does not exist, it is created)
 run: Run command_to_run inside a toolbox (if it does not exist, it is created)
 stop: Stop a running toolbox (_only_ if no active sessions exists for it)

For the create, enter and stop commands, the toolbox name can be specified either:
 - with -t/--tag, e.g.: 'toolbox enter -t dev'. For user foo, will enter 'toolbox-foo-user-dev'. Or,
 - with -c/--container, e.g.: 'toolbox create -c work'. Will create 'work'. Or
 - with just the name of the container, e.g.: 'toolbox enter test'. Will enter 'test'.

Options:
  -h/--help: Shows this help message
  -u/--user: Run as the current user inside the container
  -r/--root: Runs $CLI via sudo as root
  -X/--runtime <runtime_bin>: Use the specified runtime (e.g., /usr/bin/crun)
  -n/--nostop: Does not stop the container on exit, allowing multiple
               sessions to use the same toolbox at once
  -S/--sandbox: Start a \"less privileged than usual\" toolbox. It remains
                true, though, that toolbox is *NOT* meant to be used for when
                security and strong isolation are important. Always bear this
                in mind, even when using this option.
  -P/--no-pull: Skip trying to update the image, if it already exists. This
                may speedup toolbox creation, but at the risk of creating the
                toolbox out of a potentially (very?) old image.
  -t/--tag <tag>: Add <tag> to the toolbox name
  -c/--container <name>: Set the name of the toolbox to be equal to <name>
                         (use this alternatively to -t)
  -R/--reg <registry>: Pulls the container image from <registry>
  -I/--img <image>: Pulls the image called <image>
  -i/--image <image_URI>: Pulls <image_URI> as a container image (use this
                          alternatively to -R and -I)

You may override the following variables by setting them in ${TOOLBOXRC}:
- REGISTRY: The registry to pull from. Default: $REGISTRY
- IMAGE: The image and tag from the registry to pull. Default: $IMAGE
- TOOLBOX_NAME: The name to use for the local container. Default: $TOOLBOX_NAME
- TOOLBOX_SHELL: Standard shell if no other commands are given. Default: $TOOLBOX_SHELL

Example toolboxrc:
REGISTRY=my.special.registry.example.com
IMAGE=debug:latest
TOOLBOX_NAME=special-debug-container
TOOLBOX_SHELL=/bin/bash"
}

is_option() {
    if [ "${1:0:1}" = "-" ]; then
        return 1
    fi
    return 0
}

main() {
    # Execute setup first so we get proper variables
    setup

    # Deal with commands first. We want to support both "command mode"
    # (compatible with Silverblue's toolbox) and the current "command-less"
    # mode of operation. If wanting to use a command, that has to be the
    # first argument. If no command is provided, we basically default to
    # 'run', which is 'create, start and fire a shell inside the toolbox'.
    #
    # Note that, if a command is used, we set  "user" mode by default (i.e.,
    # even if `-u` is not specified later). This is again for compatibility
    # with https://github.com/containers/toolbox).
    COMMAND=run
    if [ -n "$1" ] && is_option $1 ; then
        case $1 in
            create | list | enter | run | stop)
                MODE="user"
                COMMAND=$1
                shift
                ;;
        esac
    fi

    ARGS=$(getopt -o hrunSPt:R:I:c:i:X: --long help,root,user,nostop,sandbox,no-pull,tag:,reg:,img:,container:,image:,runtime: -n toolbox -- "$@")
    eval set -- "$ARGS"
    while true; do
        case "$1" in
            -h|--help)
                # If we are passed a help switch, show help and exit
                show_help
                exit 0
                ;;
            -r|--root)
                shift
                SUDO=sudo
                ;;
            -X|--runtime)
                RUNTIME="--runtime $2"
                if ! command -v $2 &> /dev/null ; then
                    echo "ERROR: $2 not available as runtime!"
                    show_help
                    exit 1
                fi
                shift 2
                ;;
            -u|--user)
                shift
                MODE="user"
                ;;
            -n|--nostop)
                NO_STOP="true"
                shift
                ;;
            -S|--sandbox)
                echo "WARNING: toolbox is not for sandboxing. Using -S removes some privileges, but don't feel too safe!!!"
                SANDBOX="true"
                shift
                ;;
            -P|--no-pull)
                NO_PULL="true"
                shift
                ;;
            -c|--container)
                if [ -n "$TAG" ]; then
                    echo "ERROR: Don't use both -c and -t!"
                    show_help
                    exit 1
                fi
                CHANGE_NAME="true"
                TOOLBOX_NAME="$2"
                shift 2
                ;;
            -t|--tag)
                if [ -n "$CHANGE_NAME" ]; then
                    echo "ERROR: Don't use both -c and -t!"
                    show_help
                    exit 1
                fi
                TAG="$2"
                shift 2
                ;;
            -R|--reg)
                REGISTRY=$2
                shift 2
                ;;
            -I|--img)
                IMAGE=$2
                shift 2
                ;;
            -i|--image)
                REGISTRY=""
                IMAGE=$2
                shift 2
                ;;
            --)
                shift
                break
                ;;
            *)
                echo "unknown parameter: '$1'"
                show_help
                exit 1
                ;;
        esac
    done

    ${SUDO} ${CLI} ps &> /dev/null
    if [ $? -ne 0 ]; then
        echo "$0: ERROR: '${CLI}' is available but does not seem to be usable. Exiting!"
    fi

    # Let's rebuild the image URI (this means that command
    # line, if present, overrides config file)
    TOOLBOX_IMAGE=$(echo "${REGISTRY}"/"${IMAGE}" | sed 's/^\///g')

    if [ "$MODE" = "user" ]; then
        local USER_ENV="DBUS_SESSION_BUS_ADDRESS \
            DBUS_SYSTEM_BUS_ADDRESS \
            DESKTOP_SESSION \
            SESSION_MANAGER \
            DISPLAY \
            LANG \
            SSH_AUTH_SOCK \
            USER \
            USERNAME \
            WAYLAND_DISPLAY \
            XAUTHORITY \
            XAUTHLOCALHOSTNAME \
            XDG_CURRENT_DESKTOP \
            XDG_DATA_DIRS \
            XDG_MENU_PREFIX \
            XDG_RUNTIME_DIR \
            XDG_SESSION_CLASS \
            XDG_SESSION_DESKTOP \
            XDG_SESSION_TYPE"

        USER_ID=$(id -u); USER_GID=$(id -g)
        USER_NAME=$(id -un) ; USER_GNAME=$(id -gn)
        if [ -z "$CHANGE_NAME" ]; then
            TOOLBOX_NAME="${TOOLBOX_NAME}-user"
        fi

        # We want to keep the pid namespace of the running user.
        # We, however, use root:root while creating, so that later we
        # can modify the user's name, groups, etc, within the container.
        VOLUMES="--volume /tmp:/tmp:rslave"
        test -d "${HOME}" && VOLUMES="$VOLUMES --volume ${HOME}:${HOME}"
        test -d "/run/user/${USER_ID}" && VOLUMES="$VOLUMES --volume /run/user/${USER_ID}:/run/user/${USER_ID}:rslave"
        test -d /run/media && VOLUMES="$VOLUMES --volume /run/media/:/run/media/:rslave"
        CREATE_AS_USER="--user root:root $VOLUMES"
	if  [[ "$CLI" == "podman" ]]; then
            # Let's retain the user's groupd. This will (probably) only work
            # with some runtime, but it's harmless for other, so worth a try.
            CREATE_AS_USER="$CREATE_AS_USER --annotation run.oci.keep_original_groups=1"
	    # userns=keep-id only works if being used rootless
            if  [[ -z $SUDO ]]; then
                CREATE_AS_USER="$CREATE_AS_USER --userns=keep-id"
            fi
        fi
        for ENV in $USER_ENV ; do
            eval VAL="$""$ENV"
            [[ -n "$VAL" ]] && USER_ENV_ARR+=(--env "$ENV=$VAL")
        done
        EXEC_AS_USER=(--user "${USER_ID}:${USER_GID}" -w "$(pwd)" "${USER_ENV_ARR[@]}")
    fi

    if [ -n "$TAG" ]; then
        TOOLBOX_NAME="${TOOLBOX_NAME}-$TAG"
    fi

    # enter, create and stop supports the name of the container being as an
    # argument, so use if it's there. But there must be no conflict between
    # that and the -c and -t options.
    if [ "$COMMAND" = "enter" ] || [ "$COMMAND" = "create" ] || [ "$COMMAND" = "stop" ]; then
        if [ $# -ge 1 ]; then
            if [ -n "$CHANGE_NAME" ] || [ -n "$TAG" ]; then
                echo "ERROR: Cannot determine which container to use between $TOOLBOX_NAME and $1"
                show_help
                exit 1
            fi
            TOOLBOX_NAME=$1
            shift
        fi
    fi

    case $COMMAND in
        create|enter|run)
            # Cleanup is only needed if we're really starting the container
            trap cleanup EXIT

            if [ "$COMMAND" = "create" ]; then
                [ $# -gt 0 ] && echo "WARNING: ignoring the following arguments: $@"
                create
            elif [ "$COMMAND" = "enter" ] || [ $# -eq 0 ]; then
                [ "$COMMAND" = "enter" ] && [ $# -gt 0 ] && echo "WARNING: ignoring the following arguments: $@"
                run ${TOOLBOX_SHELL}
            else
                run "$@"
            fi
            ;;
        list|stop)
            $COMMAND
            ;;
        *)
            echo "unknown command: '$COMMAND'"
            exit 1
            ;;
    esac
}

main "$@"
