#!/usr/bin/env bash
set -euo pipefail
umask 077
E="/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-certification-deployment-6aaef77de87489c3be493978645781b24b55ab07513ff1f880164741d0bd3c73-st_01a00b39";C="/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-inode-test-fix-successor-6aaef77de87489c3be493978645781b24b55ab07513ff1f880164741d0bd3c73";P=/home/cube/.hermes/profiles/dualcoachtest;S="$P/workspace/checkin_cli";PY=/home/cube/projects/richard/hermes-agent/.venv/bin/python;W="$C/artifacts/physique_checkin_cli-0.1.0-py3-none-any.whl";UNIT=hermes-gateway-dualcoachtest.service
record(){ local n="$1";shift;local o="$E/artifacts/$n" s e rc;mkdir -p "$o";printf '%q ' "$@">"$o/command.txt";echo>>"$o/command.txt";date -u +%Y-%m-%dT%H:%M:%S.%NZ>"$o/started-at-utc.txt";s=$(date +%s%N);set +e;"$@">"$o/stdout.txt" 2>"$o/stderr.txt";rc=$?;set -e;e=$(date +%s%N);date -u +%Y-%m-%dT%H:%M:%S.%NZ>"$o/ended-at-utc.txt";echo "$rc">"$o/exit-code.txt";echo "$(((e-s)/1000000))">"$o/duration-ms.txt";(cd "$o"&&sha256sum command.txt started-at-utc.txt ended-at-utc.txt exit-code.txt duration-ms.txt stdout.txt stderr.txt>files.sha256);return "$rc";}
sha256sum -c "$E/receipts/gate-receipt-hashes.sha256"
[[ $(sha256sum "$W"|cut -d' ' -f1) == f75856d6d986b64d3d2f083aec2f865c7aea19f5950b84ff06e519f2f6505af6 ]]
record deploy-candidate-reverify "$PY" "$C/verify_candidate.py" "$C"
sha256sum "$P/customers/registry.json" "$P/data/onboarding/telegram-customer-bootstrap-v1/ledger.json" "$P/data/customers/task26_live_2e_r2_20260815_8527916639/nutrition-onboarding/readiness-receipt-v1.json">"$E/artifacts/deploy-authority-before.sha256"
record deploy-wheel-install "$PY" -m pip install --no-deps --force-reinstall "$W"
record deploy-installed-proof env -C /tmp -u PYTHONPATH PYTHONDONTWRITEBYTECODE=1 "$PY" -B - "$W" <<'PY'
import hashlib,importlib,json,sys
from importlib import metadata
from pathlib import Path
from urllib.parse import unquote,urlparse
w=Path(sys.argv[1]).resolve();dist=metadata.distribution('physique-checkin-cli');direct=dist._path/'direct_url.json';d=json.loads(direct.read_text());url=Path(unquote(urlparse(d['url']).path)).resolve();archive=d.get('archive_info',{}).get('hash');rows=[]
for n in ['checkin_cli.customer_admin','checkin_cli.activation_token_rotation_policy']:
 m=importlib.import_module(n);p=Path(m.__file__).resolve();rows.append({'module':n,'path':str(p),'sha256':hashlib.sha256(p.read_bytes()).hexdigest()})
o={'direct_url_path':str(direct),'direct_url':d,'resolved_wheel':str(url),'expected_wheel':str(w),'wheel_sha256':hashlib.sha256(w.read_bytes()).hexdigest(),'archive_hash':archive,'modules':rows};o['status']='PASS' if url==w and archive=='sha256=f75856d6d986b64d3d2f083aec2f865c7aea19f5950b84ff06e519f2f6505af6' and [x['sha256'] for x in rows]==['6ed04abb8788108de88fc439ebf3a24352cc0657a69f2efc09b50e2897cddd5e','22533ac128f41c3b82a323394a9dad050985a8be0c8d498eb56eca9980a58b1f'] else 'FAIL';print(json.dumps(o,sort_keys=True,separators=(',',':')));raise SystemExit(o['status']!='PASS')
PY
record deploy-profile-proof "$PY" - "$S" <<'PY'
import hashlib,json,sys
from pathlib import Path
s=Path(sys.argv[1]);expected={'checkin_cli/customer_admin.py':'6ed04abb8788108de88fc439ebf3a24352cc0657a69f2efc09b50e2897cddd5e','checkin_cli/activation_token_rotation_policy.py':'22533ac128f41c3b82a323394a9dad050985a8be0c8d498eb56eca9980a58b1f','tests/test_adaptive_nutrition.py':'0831230dbebb27303a55d9ac2cb349adb217cd639d1db2981eab0974db527354'};rows=[{'path':p,'sha256':hashlib.sha256((s/p).read_bytes()).hexdigest(),'expected':h} for p,h in expected.items()];o={'files':rows,'status':'PASS' if all(x['sha256']==x['expected'] for x in rows) else 'FAIL'};print(json.dumps(o,sort_keys=True,separators=(',',':')));raise SystemExit(o['status']!='PASS')
PY
record deploy-service-restart systemctl --user restart "$UNIT"
record deploy-service-health "$PY" - "$UNIT" <<'PY'
import json,subprocess,sys
u=sys.argv[1];p=subprocess.run(['systemctl','--user','show',u,'-p','ActiveState','-p','SubState','-p','MainPID','-p','Result','-p','InvocationID','-p','ExecMainStartTimestamp'],text=True,capture_output=True,check=True);d=dict(x.split('=',1) for x in p.stdout.splitlines() if '=' in x);pid=int(d['MainPID']);d['process_alive']=pid>0 and subprocess.run(['kill','-0',str(pid)],capture_output=True).returncode==0;d['status']='PASS' if d['ActiveState']=='active' and d['SubState']=='running' and d['process_alive'] else 'FAIL';print(json.dumps(d,sort_keys=True,separators=(',',':')));raise SystemExit(d['status']!='PASS')
PY
INV=$(systemctl --user show "$UNIT" -p InvocationID --value);journalctl --user _SYSTEMD_INVOCATION_ID="$INV" --no-pager -o short-iso >"$E/artifacts/deploy-service-journal.txt"
PID=$(systemctl --user show "$UNIT" -p MainPID --value);tr '\0' ' ' <"/proc/$PID/cmdline">"$E/artifacts/deploy-service-cmdline.txt"
sha256sum "$P/customers/registry.json" "$P/data/onboarding/telegram-customer-bootstrap-v1/ledger.json" "$P/data/customers/task26_live_2e_r2_20260815_8527916639/nutrition-onboarding/readiness-receipt-v1.json">"$E/artifacts/deploy-authority-after.sha256"
cmp "$E/artifacts/deploy-authority-before.sha256" "$E/artifacts/deploy-authority-after.sha256"
"$E/run-gates.sh" after-gates
