#!/bin/bash
# =============================================== #
# devc.sh v2.2; job79, maurice                    #
# Dev container entry script.                     #
# =============================================== #
set -euo pipefail
log() { echo -e "\e[36m○\e[0m $1"; }
die() { echo -e "\e[31mx\e[0m $1" && exit 1; }

# default_args configures standard container options.
default_args() {
  run_opts+=(
    "--name" "$name"
    "--hostname" "$name"
    "--pull=newer"                      # Update image.
    "--userns=keep-id"                  # Map host user.
    "-v" "$name:/home/user:copy"        # Persistent home volume.
    "-v" "dnf-cache:/var/cache/libdnf5" # Cache dnf metadata.
  )

  # Unix sockets require SELinux label disable.
  [[ -d /sys/fs/selinux ]] && run_opts+=("--security-opt" "label=disable")

  # Desktop integration (Wayland, SSH).
  [[ -e "/run/user/$UID/wayland-0" ]] && run_opts+=("-v" "/run/user/$UID/wayland-0:/run/user/1000/wayland-0")
  [[ -e "${SSH_AUTH_SOCK:-}" ]] && run_opts+=("-v" "$SSH_AUTH_SOCK:/run/user/1000/ssh-auth-sock")

  # Load custom container config.
  local config_file="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../containers/$name/config.sh"
  [[ ! -f "$config_file" ]] || source "$config_file"
}

# param_args parses CLI arguments into podman run options.
param_args() {
  while (($# > 0)); do
    case "$1" in
    -gpu) run_opts+=("--device" "/dev/dri") ;;
    -no-pull) run_opts+=("--pull=never") ;;
    -host-spawn) run_opts+=("-v" "/run/user/$UID/bus:/tmp/bus" "-e" "HOST_HOME=$HOME") ;;
    -container-sock) run_opts+=("-v" "$XDG_RUNTIME_DIR/podman/podman.sock:/var/run/docker.sock") ;;
    -x11) run_opts+=("-v" "/tmp/.X11-unix:/tmp/.X11-unix" "-v" "$XAUTHORITY:/run/user/1000/.Xauthority:ro" "-e" "DISPLAY=$DISPLAY" "-e" "XAUTHORITY=/run/user/1000/.Xauthority") ;;
    -mnt) shift && run_opts+=("-w" "/mnt/" "-v" "$(realpath "$1"):/mnt/$([[ -d "$1" ]] || echo "file")") ;;
    *) run_opts+=("$1") ;;
    esac
    shift
  done
}

main() {
  local state_file="$HOME/.local/share/devc-previous-container"
  local image="${1:-}"

  # Resolve container name (CLI arg > Last used > Error).
  if [[ $image && $image != -* ]]; then
    shift
    [[ $image != *:* ]] && image+=":main"
    mkdir -p "${state_file%/*}" && echo "$image" >"$state_file"
  elif [[ -f $state_file ]]; then
    image=$(<$state_file)
  else
    die "no container name specified"
  fi
  local name="${image%:*}" tag="${image#*:}"
  image="$name" # config.sh may override (e.g. image=base).

  # Start/Restart if not running or if arguments change configuration.
  if [[ -z "$(podman ps -q -f name="^$name$" -f status=running)" ]] || (($# > 0)); then
    log "starting $name:$tag..."

    default_args
    param_args "$@"

    podman run --replace --stop-timeout 0 -td "${run_opts[@]}" "${DEVC_REGISTRY:-git.plabble.org/job79}/$image:$tag"
  fi

  exec podman exec --detach-keys "ctrl-@,ctrl-@" -it "$name" ${DEVC_COMMAND:-bash -l}
}

main "$@"
