#!/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=

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

MODE="system"

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"

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

create() {
    if ! image_exists; then
        image_pull
    fi

    local msg="creat"
    local runlabel
    runlabel=$(image_runlabel) ||:
    if ! container_exists; then
        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: podman rm '$TOOLBOX_NAME')"
        msg="start"
    fi

    local state
    state=$(container_state)
    if [[ "$state" == configured ]] || [[ "$state" == exited ]] || [[ "$state" == stopped ]]; 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
  zypper install -y --no-recommends sudo
fi
mkdir -p /etc/sudoers.d/ && echo "${USER_NAME} ALL = (root) NOPASSWD:ALL" > /etc/sudoers.d/${USER_NAME}
EOF
        ${SUDO} podman exec --user root "${TOOLBOX_NAME}" bash "${tmp_user_setup}" &> "${tmp_user_setup_log}"
        ${SUDO} podman 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() {
    ${SUDO} podman stop "$TOOLBOX_NAME" &>/dev/null
    ${SUDO} rm -f $tmp_user_setup
}

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

container_state() {
    ${SUDO} podman inspect "$TOOLBOX_NAME" --format '{{.State.Status}}'
}

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

image_runlabel() {
    ${SUDO} podman 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 podman 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} podman pull "$TOOLBOX_IMAGE"
}

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

container_create() {
    if ! ${SUDO} podman create \
                 --hostname "$TOOLBOX_NAME" \
                 --name "$TOOLBOX_NAME" \
                 --network host \
                 --privileged \
                 --security-opt label=disable ${CREATE_AS_USER} \
                 --volume /:/media/root:rslave \
                 --volume /dev:/dev:rslave \
                 --volume /sys:/sys:rslave \
                 --volume /etc/machine-id:/etc/machine-id:ro \
                 --volume /etc/localtime:/etc/localtime:ro \
                 "$TOOLBOX_IMAGE" sleep +Inf 2>&1; then
        echo "$0: failed to create container '$TOOLBOX_NAME'"
        exit 1
    fi
}

container_start() {
    if ! ${SUDO} podman start "$TOOLBOX_NAME" 2>&1; then
        echo "$0: failed to start container '$TOOLBOX_NAME'"
        exit 1
    fi
}

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

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

show_help() {
    echo "USAGE: toolbox [[-h/--help] | [command] [-r/--root] [-u/--user]
        [[-R/--reg <registry>] [-I/--img <image>]|[-i/--image <image_URI>]]
        [[-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 podman 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)

Options:
  -h/--help: Shows this help message
  -u/--user: Run as the current user inside the container
  -r/--root: Runs podman via sudo as root
  -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 )
                MODE="user"
                COMMAND=$1
                shift
                ;;
        esac
    fi

    ARGS=$(getopt -o hrut:R:I:c:i: --long help,root,user,tag:,reg:,img:,container:,image: -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
                ;;
            -u|--user)
                shift
                MODE="user"
                ;;
            -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

    # Handle list before setting up the cleanup trap, as we won't need
    # to try to stop the container, in that case
    if [ "$COMMAND" == "list" ]; then
        list
    fi

    # Don't call trap before, else we will cleanup stuff
    # where nothing is to cleanup and report wrong error
    trap cleanup EXIT

    # 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
        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="--pid host --ipc host --userns=keep-id --user root:root $VOLUMES"
        for ENV in $USER_ENV ; do
            eval VAL="$""$ENV"
            [[ -n "$VAL" ]] && USER_ENV_STR="$USER_ENV_STR --env $ENV=$VAL"
        done
        EXEC_AS_USER="--user ${USER_ID}:${USER_GID} -w $(pwd) $USER_ENV_STR"
    fi

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

    case $COMMAND in
        create)
            create
            ;;
        enter|run)
            if [ -z "$*" ]; then
                run ${TOOLBOX_SHELL}
            else
                run "$@"
            fi
            cleanup
            ;;
        *)
            echo "unknown command: '$COMMAND'"
            exit 1
            ;;
    esac
}

main "$@"
