#!/bin/sh
# Check a downloaded chaos-encryptor-offline.zip against its published SHA-256 fingerprint.
#
#   sh verify-offline.sh chaos-encryptor-offline.zip <expected-hash>
#
# Copy <expected-hash> from the Verify page (verify.html). If you leave it out, the script looks
# for chaos-encryptor-offline.zip.sha256 next to the zip.
set -eu

ZIP="${1:-chaos-encryptor-offline.zip}"
EXPECTED="${2:-}"

if [ ! -f "$ZIP" ]; then
  echo "Cannot find $ZIP" >&2
  exit 2
fi

if [ -z "$EXPECTED" ] && [ -f "$ZIP.sha256" ]; then
  EXPECTED="$(cut -d' ' -f1 < "$ZIP.sha256")"
fi
if [ -z "$EXPECTED" ]; then
  echo "Give the expected hash from the Verify page as the second argument." >&2
  exit 2
fi

if command -v sha256sum >/dev/null 2>&1; then
  ACTUAL="$(sha256sum "$ZIP" | cut -d' ' -f1)"
else
  ACTUAL="$(shasum -a 256 "$ZIP" | cut -d' ' -f1)"
fi

EXPECTED="$(printf '%s' "$EXPECTED" | tr 'A-F' 'a-f' | tr -d ' \r\n')"
echo "Expected: $EXPECTED"
echo "Actual:   $ACTUAL"
if [ "$ACTUAL" = "$EXPECTED" ]; then
  echo "MATCH - the download is intact."
  exit 0
fi
echo "DIFFERENT - do not use this zip. Delete it and download again." >&2
exit 1
