#!/usr/bin/env nix-shell
#!nix-shell -p go-containerregistry.crane -p jq -i bash

set -euo pipefail

repo="index.docker.io/octobus/heptapod"
path="nix.docker.heptapod"
depot="$(pwd | grep -o '.*/depot')"

want_tag="latest"
if [[ ! -z "$1" ]]; then
  want_tag="$1"
fi

latest_digest="$(crane digest "$repo:$want_tag")"
current_digest="$(jq -r .imageDigest image.json)"

if [[ "$latest_digest" == "$current_digest" ]]; then
  echo already up to date
  exit 0
fi

crane ls "$repo" | grep -E '^([0-9]+\.)+[0-9]+$' | sort -rV | while read -r tag; do
  tag_digest="$(crane digest "$repo:$tag")"
  if [[ "$tag_digest" == "$latest_digest" ]]; then
    echo "$tag $tag_digest"

    mv image.json image.orig.json
    jq ".finalImageTag = \"$tag\" | .imageDigest = \"$tag_digest\" | .sha256 = \"sha256:0000000000000000000000000000000000000000000000000000\"" image.orig.json > image.json

    nix-build "$depot" --no-out-link -A "$path.meta.origImage" 2>"image.fetchlog" >/dev/null || true
    new_hash=$(sed '1,/hash mismatch in fixed-output derivation/d' "image.fetchlog" | grep --perl-regexp --only-matching 'got: +.+[:-]\K.+' | head -n +1)
    if [[ -z "$new_hash" ]]; then
      echo "Couldn't figure out new hash"
      exit 1
    fi

    jq ".finalImageTag = \"$tag\" | .imageDigest = \"$tag_digest\" | .sha256 = \"$new_hash\"" image.orig.json > image.json
    rm image.fetchlog image.orig.json
    break
  fi
done
exit $?