#!/usr/bin/env bash
#
# ONE OWNER WITH TWO-STEP SIGN-IN, ENROLLED THROUGH THE REAL PAGES (round 809).
#
#   bin/prod-image-enrol-mfa.sh https://localhost:8443
#
# The owner of a second workspace, `two-step-care` (made beforehand by
# bin/prod-image-workspace.php, because round 933 closed the sign-up page in
# production), sets two-step
# verification up at their first sign-in (round 891) with a code computed from
# the key the page shows (RFC 6238: SHA-1, 6 digits, 30 seconds). Afterwards the database
# holds one second-factor secret sealed with the running release's key — what
# the restore drill needs to prove that a release given another key is not
# ready (INV-190). Run it only against a database made for it.
#
# Needs curl and python3.

set -uo pipefail

base=${1:?usage: prod-image-enrol-mfa.sh BASE_URL}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
jar=$work/cookies

page() { curl -sk -c "$jar" -b "$jar" -o "$work/body" -w '%{http_code}' -m 30 "$@"; }
die() { echo "FAIL  $*"; exit 1; }

# Round 891 (ADR 0032 (4)): an Owner sets the second factor up at sign-in,
# before they are signed in, rather than later from the security page.
"$(dirname "$0")/prod-image-sign-in.sh" "$base" two-step-care kim@example.org 'another long passphrase 17!' "$work/kim.key" "$jar" \
    | grep -q '^signed in$' || die "sign-in did not set two-step verification up"
[ -s "$work/kim.key" ] || die "the sign-in offered no key to set up"

page "$base/settings/security" >/dev/null
grep -q 'Two-step verification on' "$work/body" || die "the security page does not say two-step verification is on"
echo "ok    two-step sign-in enrolled for the owner of two-step-care"
