#!/usr/bin/bash

DEV=$1
KEYFILE=$2

function is_empty {
    local dir="$1"
    shopt -s nullglob
    local files=( "$dir"/* "$dir"/.* )
    [[ ${#files[@]} -eq 2 ]]
}

# Do nothing if no TPM devices
if is_empty /sys/class/tpm; then
    exit
fi

# Do nothing if block device doesn't exist
if test ! -b $DEV ; then
    exit
fi

# 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
