#!/usr/bin/env bash
# Selected stopped-host relocation. Export retires the source; never use a live host.
set -eu
umask 077
: "${CHIO_STATE:?Set the existing stopped disposable host directory}"
: "${CHIO_RESTORE:?Set a new absolute destination directory}"
: "${CHIO_EVIDENCE:?Set a new absolute evidence directory outside the host}"
case "$CHIO_RESTORE" in /*) ;; *) echo 'Destination must be absolute' >&2; exit 2;; esac
case "$CHIO_EVIDENCE" in /*) ;; *) echo 'Evidence directory must be absolute' >&2; exit 2;; esac
python3 "$(dirname "$0")/relocate_check.py" paths "$CHIO_STATE" "$CHIO_RESTORE" "$CHIO_EVIDENCE"
if [ -e "$CHIO_RESTORE" ] || [ -e "$CHIO_EVIDENCE" ]; then
  echo 'Refuse to overwrite a destination or evidence directory' >&2
  exit 2
fi
mkdir -m 0700 "$CHIO_EVIDENCE"
chio process status --state "$CHIO_STATE" > "$CHIO_EVIDENCE/before-status.json"
chio receipt list --receipt-db "$CHIO_STATE/receipts.db" --admin-all --limit 100 \
  > "$CHIO_EVIDENCE/before-receipts.jsonl" 2> "$CHIO_EVIDENCE/before-page.stderr"
chio process export --state "$CHIO_STATE" > "$CHIO_EVIDENCE/export.json"
cp "$CHIO_STATE/relocation.json" "$CHIO_EVIDENCE/original-relocation.json"
cp -a "$CHIO_STATE" "$CHIO_RESTORE"
chio process import --state "$CHIO_RESTORE" > "$CHIO_EVIDENCE/import.json"
chio process status --state "$CHIO_RESTORE" > "$CHIO_EVIDENCE/after-status.json"
chio receipt list --receipt-db "$CHIO_RESTORE/receipts.db" --admin-all --limit 100 \
  > "$CHIO_EVIDENCE/after-receipts.jsonl" 2> "$CHIO_EVIDENCE/after-page.stderr"
# This compares the selected first page, not proof of complete receipt history.
cmp "$CHIO_EVIDENCE/before-receipts.jsonl" "$CHIO_EVIDENCE/after-receipts.jsonl"
python3 "$(dirname "$0")/relocate_check.py" identity "$CHIO_EVIDENCE"
