#!/bin/sh
# Runtime checks on the built media libraries, on a Windows PC (Git Bash), after build.sh:
# every dist/ file hashes to MANIFEST.json; the x64 ffmpeg.exe and ffprobe.exe run and state the
# LGPL, an LGPL-only configuration without network, exactly the file and pipe protocols, the Media
# Foundation and LAME encoders and no GPL or cloud-only codec or muxer. The arm64 files are
# inspected (hash and PE machine), not executed. Writes nothing.
#   sh apps/windows/ffmpeg/verify.sh
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
DIST="$HERE/dist"
PYTHON=${PYTHON:-$(command -v python3 2>/dev/null || command -v python 2>/dev/null || printf python3)}
[ -d "$DIST" ] || { echo "verify: FAIL: no dist/ (build first, see README.md)"; exit 1; }
n=0
ok() { n=$((n + 1)); }
die() { echo "verify: FAIL: $*"; exit 1; }

# Hashes and machines: every manifest file, both architectures.
count=$("$PYTHON" - "$HERE" <<'PY'
import hashlib, json, os, struct, sys
here = sys.argv[1]
m = json.load(open(os.path.join(here, "MANIFEST.json"), encoding="utf-8"))
codes = {"AMD64": 0x8664, "ARM64": 0xAA64}
dist = os.path.join(here, "dist")
found = set()
for entry in os.listdir(dist):
    if os.path.isdir(os.path.join(dist, entry)):
        found |= {entry + "/" + n for n in os.listdir(os.path.join(dist, entry))}
    elif entry != "MANIFEST.json":
        found.add(entry)
if found != set(m["files"]):
    sys.exit("verify: FAIL: dist/ must hold exactly the manifest's files (extra %s, missing %s)"
             % (sorted(found - set(m["files"])), sorted(set(m["files"]) - found)))
for f, info in sorted(m["files"].items()):
    p = os.path.join(here, "dist", f)
    if not os.path.exists(p):
        sys.exit("verify: FAIL: dist is missing %s" % f)
    data = open(p, "rb").read()
    if hashlib.sha256(data).hexdigest() != info["sha256"]:
        sys.exit("verify: FAIL: dist/%s does not match MANIFEST.json" % f)
    pe = struct.unpack_from("<I", data, 0x3C)[0]
    if data[:2] != b"MZ" or data[pe:pe + 4] != b"PE\0\0" or struct.unpack_from("<H", data, pe + 4)[0] != codes[info["machine"]]:
        sys.exit("verify: FAIL: dist/%s is not a %s PE file" % (f, info["machine"]))
print(len(m["files"]))
PY
) || exit 1
[ "$count" -eq 18 ] || die "MANIFEST.json lists $count files, expected 18"
ok

FF="$DIST/win-x64/ffmpeg.exe"
FP="$DIST/win-x64/ffprobe.exe"
run() { "$@" 2>&1 | tr -d '\r'; }

L=$(run "$FF" -hide_banner -L | tr '\n' ' ' | tr -s ' ')
case "$L" in *"GNU Lesser General Public License"*) ;; *) die "ffmpeg -L does not name the GNU Lesser General Public License" ;; esac
ok
case "$L" in *"version 2.1 of the License, or"*) ;; *) die "ffmpeg -L does not state version 2.1 or later" ;; esac
ok

B=$(run "$FF" -hide_banner -buildconf)
printf '%s\n' "$B" | grep -qE -- '--enable-(gpl|nonfree|version3)' && die "ffmpeg -buildconf enables gpl, nonfree or version3"
ok
printf '%s\n' "$B" | grep -q -- '--disable-network' || die "ffmpeg -buildconf lacks --disable-network"
ok

P=$(run "$FF" -hide_banner -protocols)
IN=$(printf '%s\n' "$P" | sed -n '/^Input:/,/^Output:/p' | sed '1d;$d' | tr -d ' ' | LC_ALL=C sort | tr '\n' ',')
OUT=$(printf '%s\n' "$P" | sed -n '/^Output:/,$p' | sed '1d' | tr -d ' ' | grep . | LC_ALL=C sort | tr '\n' ',')
[ "$IN" = "file,pipe," ] || die "input protocols are '$IN', expected file,pipe"
ok
[ "$OUT" = "file,pipe," ] || die "output protocols are '$OUT', expected file,pipe"
ok

E=$(run "$FF" -hide_banner -encoders)
for e in h264_mf hevc_mf aac_mf libmp3lame; do
    printf '%s\n' "$E" | grep -q " $e " || die "encoder $e missing"
    ok
done
printf '%s\n' "$E" | grep -qE ' (libx264|libx265|libfdk_aac|libvpx|libvpx-vp9|libvorbis|libopus) ' && die "a GPL, nonfree or cloud-only encoder is present"
ok
ENCS=$(printf '%s\n' "$E" | awk 'f && NF >= 2 {print $2} /^ *--/ {f=1}' | LC_ALL=C sort | tr '\n' ' ')
[ "$ENCS" = "aac_mf flac gif h264_mf hevc_mf libmp3lame pcm_s16be pcm_s16le wmav2 " ] || die "encoders are '$ENCS', expected exactly the pinned nine"
ok

M=$(run "$FF" -hide_banner -muxers | awk 'f && NF >= 2 {print $2} /^ *--/ {f=1}')
printf '%s\n' "$M" | grep -qE '(^|,)(webm|ogg|opus|oga)(,|$)' && die "a WebM, OGG or Opus muxer is present"
ok
MUXS=$(printf '%s\n' "$M" | LC_ALL=C sort | tr '\n' ' ')
[ "$MUXS" = "adts aiff asf avi flac gif ipod matroska mov mp3 mp4 wav " ] || die "muxers are '$MUXS', expected exactly the pinned twelve"
ok

run "$FP" -hide_banner -version | grep -q '^ffprobe version' || die "ffprobe -version does not run"
ok

echo "verify: OK $n checks"
