#!/usr/bin/env bash
set -euo pipefail
[[ $# -eq 1 ]] || { echo "usage: web-deps-verify RELEASE" >&2; exit 2; }
release="$(realpath -e "$1")"
[[ -d "$release/node_modules" && ! -L "$release/node_modules" ]] || { echo "release has no dependency snapshot: $release" >&2; exit 1; }
RELEASE="$release" python3 - <<'PY'
import os
from collections import Counter
release = os.path.realpath(os.environ["RELEASE"])
inodes = Counter()
paths = []
for root, dirs, files in os.walk(os.path.join(release, "node_modules")):
    for name in dirs + files:
        path = os.path.join(root, name)
        if os.path.islink(path) and os.path.commonpath((release, os.path.realpath(path))) != release:
            raise SystemExit(f"external dependency symlink: {path}")
        if not os.path.islink(path) and os.path.isfile(path):
            stat = os.stat(path)
            key = (stat.st_dev, stat.st_ino)
            inodes[key] += 1
            paths.append((path, key, stat.st_nlink))
for path, key, links in paths:
    if links > inodes[key]:
        raise SystemExit(f"dependency hardlink escapes release: {path}")
PY
