repo_root := justfile_directory() / ".."

cntr_mgr_exe := "docker"
cntr_registry_hostname := "docker.nix-community.org"
cntr_registry_fqn := cntr_registry_hostname

ci_cntr_repo_root := "/workdir"
ci_cntr_image_name := "nixpkgs/nix-flakes"
ci_cntr_image_tag := "nixos-23.11"
ci_cntr_image_fqn := cntr_registry_fqn / ci_cntr_image_name
ci_cntr_name := "fundamentum-edge-daemon-ci-nix-flake"
ci_cntr_cmd_def := ci_cntr_repo_root / ".ci/bin/runner" + " bash"

# Build and load the CI container image.
ci-container: _ci-container-image-pull

# Clean our CI container image alongside with any related artifacts.
ci-container-clean: _ci-container-instance-clean _ci-container-image-clean

# Run a command (defaults to 'nix develop -i -c bash') within the CI container
# image.
ci-container-run cmd=ci_cntr_cmd_def: _ci-container-image-pull (_ci-container-run cmd)

# Run a command (defaults to 'nix develop -i -c bash') within the CI container
# image assuming the image is already available.
ci-container-run-only cmd=ci_cntr_cmd_def: (_ci-container-run cmd)

_ci-container-run cmd:
    @{{ cntr_mgr_exe }} run -it --rm \
      --mount "type=bind,source={{ repo_root }},target={{ ci_cntr_repo_root }}" \
      --workdir="{{ ci_cntr_repo_root }}" \
      --name "{{ ci_cntr_name }}" \
      "{{ ci_cntr_image_fqn }}:{{ ci_cntr_image_tag }}" \
      {{ cmd }}

_ci-container-instance-clean:
    @if {{ cntr_mgr_exe }} container inspect \
      -f '{{{{.State.Running}}' "{{ ci_cntr_name }}" &>/dev/null; \
    then \
      {{ cntr_mgr_exe }} rm --force "{{ ci_cntr_name }}"; \
    fi

_ci-container-image-pull:
    @{{ cntr_mgr_exe }} pull "{{ ci_cntr_image_fqn }}:{{ ci_cntr_image_tag }}"

_ci-container-image-clean:
    @( {{ cntr_mgr_exe }} images -q "{{ ci_cntr_image_name }}" \
       && {{ cntr_mgr_exe }} images -q "{{ ci_cntr_image_fqn }}" ) \
     | sort | uniq \
     | xargs --no-run-if-empty {{ cntr_mgr_exe }} rmi -f
