#!/usr/bin/bash
set -euo pipefail
shopt -s expand_aliases

source anti-evil-maid-lib

validatetpm || exit 1


if ! { [ $# = 0 ] || { [ $# = 1 ] && [ "$1" = "-z" ]; }; } then
    echo "Usage: ${0##*/} [-z]"
    exit 1
fi

if [ "$(id -ur)" != 0 ]; then
    log "This command must be run as root!"
    exit 1
fi

if tpmowned; then
    log "You must reset/clear your TPM chip first!"
    exit 1
fi


# - take ownership of TPM

OWNERPW=$(head -c 16 /dev/random | hex)
srkpw=

if [ $# = 0 ]; then  # set an SRK password
    for try in 1 2 3; do
        read -r -s -p "Choose SRK password: "  srkpw
        echo
        read -r -s -p "Confirm SRK password: " srkpw2
        echo

        [ "$srkpw" != "$srkpw2" ] || break
        log "Passwords didn't match"
        [ "$try" != 3 ] || exit 1
    done
fi

tpmrestartservices

log "Taking ownership of the TPM..."
tpmtakeownership "$OWNERPW" "$srkpw"

echo "$OWNERPW" >"$TPM_OWNER_PASSWORD_FILE"


# - generate NVRAM ID

alias provisioned_id=false
if [[ $(tpmid 2>/dev/null) == "unknown" ]]; then
    # TPM reset does not clear NVRAM, reusing old ID is fine though
    log "Creating TPM ID..."
    provisiontpmid
    alias provisioned_id=true
fi


# - create freshness token area

if checktpmnvram; then
    # delete old freshness area as the old access password is most likely lost
    # (in case it isn't, the area will simply get recreated with the same pw)
    log "Deleting old freshness token NVRAM area..."
    destroytpmnvram "$OWNERPW"
fi
log "Creating freshness token NVRAM area..."
createtpmnvram "$OWNERPW"


# - update TPMs directory after provisioning

if provisioned_id; then
    postprovisioning
fi
