#!/bin/sh
# Build only the two libraries from the digest-verified official source.
# No make install, package manager, phone access or production credentials.
set -eu
repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$repo_dir"
source_archives="${1:-$repo_dir/.build/dependency-preparation/sources}"
build_dir="$repo_dir/.build/dependency-preparation/openssl-build"
resume="${2:-}"
case "$resume" in ''|--resume) ;; *) printf '%s\n' 'Second argument may only be --resume.' >&2; exit 2 ;; esac
/usr/bin/python3 - "$source_archives" "$build_dir" "$resume" <<'PY'
import hashlib, json, sys, tarfile
from pathlib import Path
root = Path.cwd()
source_dir, build_dir = map(Path, sys.argv[1:3])
record = next(package for package in json.loads((root / 'Configuration/ReleaseDependencies.json').read_text())['nativePackages'] if package['name'] == 'openssl@3')
archive = source_dir / record['source']['url'].rsplit('/', 1)[-1]
if hashlib.sha256(archive.read_bytes()).hexdigest() != record['source']['archiveSHA256']:
    raise SystemExit('OpenSSL source hash mismatch; no build executed.')
if build_dir.exists():
    if sys.argv[3] == '--resume':
        prior = json.loads((build_dir / ('openssl-' + record['version']) / 'thumbwise-build-record.json').read_bytes())
        if prior['sourceSHA256'] != record['source']['archiveSHA256']:
            raise SystemExit('Existing source record differs; no build executed.')
        raise SystemExit(0)
    raise SystemExit('OpenSSL build directory exists; inspect/remove only this disposable build before rebuilding.')
build_dir.mkdir(parents=True)
with tarfile.open(archive) as source:
    for item in source.getmembers():
        relative = Path(item.name)
        if relative.is_absolute() or '..' in relative.parts or not relative.parts or relative.parts[0] != 'openssl-' + record['version']:
            raise SystemExit('Unsafe source member; no build executed.')
        target = build_dir / relative
        if item.isdir():
            target.mkdir(parents=True, exist_ok=True)
        elif item.isfile():
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_bytes(source.extractfile(item).read())
            target.chmod(item.mode & 0o777)
        else:
            raise SystemExit('Linked or special source member refused; no build executed.')
PY
cd "$build_dir/openssl-3.6.4"
export MACOSX_DEPLOYMENT_TARGET=15.0
# Fixed build timestamp so the libraries do not embed the build time.
export SOURCE_DATE_EPOCH=0
# These defaults contain no Homebrew/developer paths and require no root directory
# to be created. The device bridge uses its explicit pairing material, not a
# system CA bundle. Qualification of that TLS behavior remains required.
/usr/bin/perl ./Configure darwin64-arm64-cc shared no-tests no-docs no-apps \
  no-module no-engine --prefix=/ThumbwiseRuntime --openssldir=/ThumbwiseRuntime/etc/ssl \
  --libdir=lib -O2 -g0
# Resume must regenerate the compiled version/flags metadata even when make's
# timestamp/dependency cache kept a prior cversion object after reconfiguration.
/bin/rm -f crypto/buildinf.h crypto/libcrypto-shlib-cversion.o crypto/libcrypto-lib-cversion.o
/usr/bin/make --jobs=2 build_libs
/usr/bin/python3 - "$repo_dir" <<'PY'
import hashlib, json, sys
from pathlib import Path
root = Path(sys.argv[1])
record = {
    'schemaVersion': 1, 'version': '3.6.4',
    'sourceSHA256': '9bffaa1ad1e07b354c21bd3324ec02fa15579f45a7d0494b3e74bc449b7333ef',
    'recipeSHA256': hashlib.sha256((root / 'Tools/build_release_openssl.sh').read_bytes()).hexdigest(),
    'policy': 'arm64/macOS 15.0; shared; no module/engine/apps/tests/docs; portable product prefix; no install',
    'images': {name: hashlib.sha256(Path(name).read_bytes()).hexdigest() for name in ('libssl.3.dylib', 'libcrypto.3.dylib')},
}
Path('thumbwise-build-record.json').write_text(json.dumps(record, indent=2) + '\n')
print('PASS Verified upstream OpenSSL libraries built locally with two jobs; no installation occurred.')
PY
