#!/usr/bin/env bash
# Pack or unpack a Cargo/rustup (and optional cargo-xwin) cache as one tarball.
# BlueGit `cache.paths` copies only files, not directories, so a directory
# such as cargo-home/ would otherwise be skipped (see bluegit runner saveCache).
# Does not cache target/: too large for the runner's job-cache budget.
set -euo pipefail

usage() {
  echo "usage: $0 restore|save linux|windows" >&2
  exit 2
}

cmd="${1:-}"
kind="${2:-}"
[[ "$cmd" == restore || "$cmd" == save ]] || usage
[[ "$kind" == linux || "$kind" == windows ]] || usage

archive=".ci-cache/cargo-${kind}.tar.gz"

# Locations in the job workspace (set by the CI job / ci-setup.sh).
cargo_home="${CARGO_HOME:-$PWD/cargo-home}"
rustup_home="${RUSTUP_HOME:-$PWD/rustup-home}"
xwin_cache="${XWIN_CACHE_DIR:-$PWD/xwin-cache}"

relpath() {
  local abs="$1"
  case "$abs" in
    "$PWD"/*) printf '%s\n' "${abs#"$PWD"/}" ;;
    /*) printf '%s\n' "$abs" ;;
    *) printf '%s\n' "$abs" ;;
  esac
}

if [[ "$cmd" == restore ]]; then
  if [[ -f "$archive" ]]; then
    tar -xzf "$archive"
    echo "CI-cache hersteld ($archive)."
  else
    echo "Geen CI-cache ($archive)."
  fi
  exit 0
fi

mkdir -p .ci-cache
parts=()
add_if_dir() {
  local p="$1"
  [[ -d "$p" ]] || return 0
  parts+=("$(relpath "$p")")
}

# Registry and git checkouts, not registry/src (that is rebuilt from .crate files).
add_if_dir "$cargo_home/bin"
add_if_dir "$cargo_home/registry/index"
add_if_dir "$cargo_home/registry/cache"
add_if_dir "$cargo_home/git/db"
add_if_dir "$rustup_home"
if [[ "$kind" == windows ]]; then
  add_if_dir "$xwin_cache"
fi

if [[ ${#parts[@]} -eq 0 ]]; then
  echo "Niets te cachen."
  exit 0
fi

# gzip -1: kleiner bestand voor de 10 GB-jobcache, weinig CPU.
tar -c --use-compress-program='gzip -1' -f "$archive" "${parts[@]}"
echo "CI-cache opgeslagen ($archive): ${parts[*]}"
ls -lh "$archive"
