#!/bin/bash
# Verify that this directory arrived on the offline machine complete and usable.
# Run before build-boringssl-android-offline.sh.
set -uo pipefail
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
DEPS="$SCRIPT_DIR/build-deps"
INV="$DEPS/INVENTORY.txt"
fails=0
ok()  { printf '  OK    %s\n' "$*"; }
bad() { printf '  FAIL  %s\n' "$*"; fails=$((fails+1)); }
want() { sed -n "s/^$1=//p" "$INV"; }

printf 'Checking %s\n' "$SCRIPT_DIR"
[ -f "$INV" ] || { printf 'ERROR: %s missing; re-copy the directory\n' "$INV" >&2; exit 1; }

srpm="$SCRIPT_DIR/$(want srpm)"
[ -f "$srpm" ] && ok "source RPM present" || bad "source RPM $(want srpm) MISSING"
if [ -f "$srpm" ]; then
    [ "$(sha256sum "$srpm" | cut -d' ' -f1)" = "$(want srpm_sha256)" ] \
        && ok "source RPM checksum" || bad "source RPM checksum MISMATCH"
fi

[ -d "$DEPS/rpms/repodata" ] && ok "rpms/repodata present" || bad "rpms/repodata MISSING (run createrepo_c on build-deps/rpms)"
count=$(find "$DEPS/rpms" -name '*.rpm' 2>/dev/null | wc -l)
[ "$count" = "$(want rpms_count)" ] && ok "RPM files: $count" || bad "RPM files: $count (expected $(want rpms_count))"
if [ -f "$DEPS/rpms/SHA256SUMS" ]; then
    (cd "$DEPS/rpms" && sha256sum -c --quiet SHA256SUMS >/dev/null 2>&1) \
        && ok "RPM checksums verify" || bad "RPM checksums do NOT verify"
fi

ndk="$DEPS/ndk/$(want ndk_zip)"
if [ -f "$ndk" ]; then
    size=$(stat -c %s "$ndk")
    [ "$size" = "$(want ndk_bytes)" ] && ok "NDK size: $size" || bad "NDK size: $size (expected $(want ndk_bytes))"
    [ "$(sha256sum "$ndk" | cut -d' ' -f1)" = "$(want ndk_sha256)" ] \
        && ok "NDK checksum ($(want ndk_release))" || bad "NDK checksum MISMATCH"
else
    bad "NDK zip $(want ndk_zip) MISSING"
fi

printf '\n'
if [ "$fails" = 0 ]; then
    printf 'All checks passed. Run: sudo ./build-boringssl-android-offline.sh\n'
else
    printf '%d check(s) failed. Re-copy this directory, for example:\n' "$fails"
    printf '  rsync -aH --info=progress2 BoringSSL/ user@offline:/path/BoringSSL/\n'
    exit 1
fi
