#!/usr/bin/env python3
"""Check the seal of a Pramana evidence pack.

    python3 verify_pack.py pack.json
    python3 verify_pack.py pack.json --expect <PACK_SHA256 as the installation holds it>

Every evidence pack carries a SHA-256 of its own content: in the JSON as integrity.value, at the foot
of the readable pack, and in the PACK_SHA256 column of the installation that produced it. This script
recomputes that value from the JSON you hold. If the two agree, the copy says what Pramana wrote.
With --expect it also compares against the value you read from the installation, which is what shows
that the copy is the pack the installation holds and not another one.

pack.json is the PACK column of one pack, saved as text, for example the result of
    SELECT TO_JSON(PACK) FROM PRAMANA.GOV.GOV_EVIDENCE_PACK WHERE PACK_ID = '<pack id>';
A file that wraps the pack (a result set exported as JSON, the pack as a quoted string) is accepted.

How the seal is computed, so that it can be reproduced without this script: take the pack without its
"integrity" block; write every whole number without a decimal point (75.0 becomes 75); serialise as
JSON with keys sorted, items separated by ", " and keys from values by ": ", non-ASCII characters
escaped (\\uXXXX); hash the UTF-8 bytes with SHA-256. In Python:
    hashlib.sha256(json.dumps(whole_numbers(body), sort_keys=True).encode()).hexdigest()

Standard library only. Exit status: 0 the seal holds, 1 it does not, 2 the file is not a pack.
"""
import argparse
import hashlib
import json
import sys


def whole_numbers(value):
    """75.0 and 75 are the same number, and a database that stores JSON does not keep the difference."""
    if isinstance(value, dict):
        return {k: whole_numbers(v) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [whole_numbers(v) for v in value]
    if isinstance(value, float) and value == value and abs(value) != float('inf') and value == int(value):
        return int(value)
    return value


def seal(pack):
    body = {k: v for k, v in pack.items() if k != 'integrity'}
    return hashlib.sha256(json.dumps(whole_numbers(body), sort_keys=True, default=str).encode()).hexdigest()


def find_pack(value):
    """The pack inside whatever was saved: the object itself, a quoted string holding it, or a result set."""
    if isinstance(value, str):
        try:
            return find_pack(json.loads(value))
        except ValueError:
            return None
    if isinstance(value, dict):
        if 'pack_id' in value and 'integrity' in value:
            return value
        value = list(value.values())
    if isinstance(value, list):
        for item in value:
            pack = find_pack(item)
            if pack is not None:
                return pack
    return None


def main(argv=None):
    ap = argparse.ArgumentParser(description='Check the seal of a Pramana evidence pack.')
    ap.add_argument('pack', help='the pack as JSON (the PACK column, saved as text)')
    ap.add_argument('--expect', help='PACK_SHA256 as the installation holds it')
    args = ap.parse_args(argv)
    try:
        with open(args.pack, encoding='utf-8-sig') as fh:
            pack = find_pack(json.load(fh))
    except (OSError, ValueError) as exc:
        print('cannot read %s: %s' % (args.pack, exc))
        return 2
    if pack is None or not isinstance(pack.get('integrity'), dict):
        print('%s does not hold a Pramana evidence pack (no pack_id and integrity block)' % args.pack)
        print('If a query wrote this file, check the PACK_ID in it: a query that matches no pack writes an empty file.')
        return 2
    carried, computed = str(pack['integrity'].get('value', '')).lower(), seal(pack)
    print('pack       %s' % pack.get('pack_id'))
    print('framework  %s   overall %s   generated %s' % (pack.get('framework'), pack.get('overall'), pack.get('generated_at')))
    print('carried    %s' % carried)
    print('computed   %s' % computed)
    ok = carried == computed
    if args.expect:
        expected = args.expect.strip().lower()
        print('expected   %s' % expected)
        ok = ok and computed == expected
    print('SEAL HOLDS: this copy says what Pramana wrote' + (', and it is the pack the installation holds' if args.expect else '') if ok
          else 'SEAL DOES NOT HOLD: this copy differs from what Pramana wrote' + (', or it is not the pack that value belongs to' if args.expect else ''))
    return 0 if ok else 1


if __name__ == '__main__':
    sys.exit(main())
