#!/bin/sh

set -eu

usage() {
  printf \
    'Update flake.

USAGE:
  update-flake [-h]

OPTIONS:
  -h --help\tPrint this help.\n'
}

while [ $# -ne 0 ]; do
  case $1 in
  --help | -h)
    usage >&2
    exit
    ;;
  esac
done

# Some root detection guess work...
root=$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD")
if [ ! -e "$root/scripts/update-flake" ]; then
  root=$(
    cd ..
    pwd
  )
fi

if [ -e "$root/flake.nix" ]; then
  # If running on a nix-enabled system, also update npmDepsHash.
  if type nix >/dev/null 2>&1; then
    npmDepsHash=$(nix --experimental-features 'nix-command flakes' \
      run --inputs-from "$root" nixpkgs#prefetch-npm-deps \
      -- "$root/package-lock.json")
    sed -E -e '/# npmDepsHash :/s#(hash[ ]*=[ ]*").*(".*$)#\1'"$npmDepsHash"'\2#' "$root/flake.nix" >$root/flake.nix.tmp
    mv "$root/flake.nix.tmp" "$root/flake.nix"

    nix --experimental-features 'nix-command flakes' flake update --flake git+file://"$root"
  else
    printf >&2 'Node dependencies may be out of date!
Re-run on a nix-enabled system to update npmDepsHash.\n'
  fi
fi
