#!/bin/sh
set -eu

IMAGE='registry.shore.co.il/workbench'
CONTAINER='workbench'

is_latest() {
    if ! podman image exists "$IMAGE" ||
        ! toolbox run --container "$CONTAINER" true 2>/dev/null
    then
        podman image pull "$IMAGE" || exit 1
        return 1
    fi
    current="$(podman container inspect "$CONTAINER" --format '{{ .Image }}')"
    podman image pull "$IMAGE" > /dev/null
    new="$(podman image inspect "$IMAGE" --format '{{.Digest}}')"
    [ "$new" = "$current" ] || return 1
}

update() {
    if [ -S "/tmp/tmux-$(id -u)/workbench" ] && pgrep tmux >/dev/null
    then
        toolbox run --container workbench -- tmux -L workbench kill-server
    fi
    toolbox rm --force "$CONTAINER" 2>/dev/null || true
    podman image prune --filter 'label=com.github.containers.toolbox=true' --force
    yes | toolbox create --image "$IMAGE"
}

if [ "$(hostname)" = 'toolbox' ]
then
    printf '\e[1;91m%s\e[0m\n' \
        'Cannot update the workbench container from inside the workbench container.' >&2
    exit 1
elif [ "${1:-}" = "-d" ] || [ "${1:-}" = "--dry-run" ] || [ -n "${DRY_RUN:-}" ]
then
    podman image pull "$IMAGE" > /dev/null
elif ! (is_latest)
then
    update
fi