#!/usr/bin/bash

DEV=$1
KEYFILE=$2

# Do nothing if block device doesn't exist
if test -b $DEV ; then
    # Check for an existing clevis token for this device
    if cryptsetup luksDump --dump-json-metadata $DEV | jq -e '[.tokens[] | select(.type == "clevis")] | length == 0' > /dev/null; then
        # No token, lets generate one and then kill all old slots
        OLDKEYS=$(cryptsetup luksDump --dump-json-metadata $DEV | jq '.keyslots | keys[] | tonumber')
        clevis luks bind -k $KEYFILE -d $DEV tpm2 '{}'
        for OLDKEY in $OLDKEYS; do
            cryptsetup luksKillSlot -q $DEV $OLDKEY;
        done
    fi
fi
