#!/usr/bin/env -S just --working-directory . --justfile

image := "ghcr.io/jswank/alpine-cli:3"
n := "alpine-cli"

# Invoke the 'run' recipe
default: run

# Usage: run
#
# Start a shell in an ephemeral container.
#
# Examples:
#   cli run
#
# Run an ephemeral container.
@run run_args="":
  podman run -ti --userns=keep-id --rm {{run_args}} {{image}}

# Usage: persist
#
# Start a shell in a persistent container.
#
# Examples:
#   cli persist
#
# Run (or attach to) a persistent container
persist: 
  #!/bin/sh
  if [ $(podman ps --all --filter name="^{{n}}$" -q | wc -l) -gt 0 ]; then
    podman start -i -a {{n}}
  else
    podman run -ti --userns=keep-id --name {{n}} {{image}}
  fi

# Pull the latest version of the image
@pull:
  podman pull {{image}} >/dev/null 2>&1

# Remove the persistent container
@clean:
  podman rm -f {{n}} >/dev/null 2>&1

# Usage: save [new_image_name]
#
# Sometimes you want a quick snapshot of your work in progress. Use this target
# to create an image based on the running container.
#
# Examples:
#    cli save foo` - saves the current (persistent) container as a new image
#                       named "foo"
# `  cli save      - saves the current (persistent) container as a new
#                       default image
#
# Save the running container as a new image
save i=image:
  podman commit -q {{n}} {{i}} >/dev/null 2>&1

# Remove a running container, and run the default recipe
@restart: clean default

# Pull the latest published image
@update:
  podman pull {{image}}

# Display this listing. Detailed help is available with 'help recipe_name'.
help recipe="help":
  #!/bin/sh
  if [ "{{recipe}}" = "help" ]; then
    just --list --justfile {{justfile()}}
  else
    grep -B 32 -E '^@?{{recipe}}\s?.*:' {{justfile()}} \
      | tac |  awk 'NR==1 {print; next}; !/^#/{exit}1;' | tac
  fi
