#!/bin/bash

echo "Patching /etc/crypttab"

root=$($(dirname "$0")/rootdev)
if [[ -z "$root" ]]; then
    echo "$0: no root device"
    exit 1
fi

cryptroot=""
while read l; do
    id=$(echo $l | cut -f2 -d " ")
    path="$id"
    # Either it's a path or a UUID prefix
    if [[ "${path:0:1}" != "/" ]]; then
        # UUID prefix. R
        path=$(echo -n "$path" | sed 's/UUID=//g')
        path=$(blkid -U "$path")
    fi
    path=$(readlink -f "$path")
    if [[ "$path" == "$root" ]]; then
        cryptroot="$id"
        break
    fi
done < /etc/crypttab

if [[ -z "$cryptroot" ]]; then
    # did not find root device. Patch it to /etc/crypttab
    printf "rootdev %s /etc/lsvmload/rootkey luks,discard", "$root" >> /etc/crypttab
    exit 0
fi

awk -v targ="$cryptroot" '{ if ($2 == targ) { $3="/etc/lsvmload/rootkey" }; print }' /etc/crypttab > /etc/crypttab.new
mv /etc/crypttab.new /etc/crypttab
exit 0
