#!/bin/bash -e
# vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80:
#
# Copyright (c) 2017 Red Hat, Inc.
# Author: Javier Martinez Canillas <javierm@redhat.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

SUMMARY="Unbinds a pin bound to a LUKSv1 volume"
UUID=cb6e8904-81ff-40da-a84a-07ab9ab5715e

function usage() {
    echo >&2
    echo "Usage: clevis luks unbind -d DEV -s SLT" >&2
    echo >&2
    echo "$SUMMARY": >&2
    echo >&2
    echo "  -d DEV  The bound LUKS device" >&2
    echo >&2
    echo "  -s SLOT The LUKSMeta slot number for the pin unbind" >&2
    echo >&2
    echo "  -f      Do not ask for confirmation and wipe slot in batch-mode" >&2
    echo >&2
    exit 1
}

if [ $# -eq 1 -a "$1" == "--summary" ]; then
    echo "$SUMMARY"
    exit 0
fi

while getopts ":d:s:f" o; do
    case "$o" in
    f) FRC=-q;;
    d) DEV=$OPTARG;;
    s) SLT=$OPTARG;;
    *) usage;;
    esac
done

if [ -z "$DEV" ]; then
    echo "Did not specify a device!" >&2
    usage
fi

if [ -z "$SLT" ]; then
    echo "Did not specify a slot!" >&2
    usage
fi

if ! luksmeta test -d $DEV 2>/dev/null; then
    echo "The $DEV device is not valid!" >&2
    exit 1
fi

read -r slot active uuid <<< $(luksmeta show -d "$DEV" | grep "^$SLT *")

if [ "$uuid" = "empty" ]; then
   echo "The LUKSMeta slot $SLT on device $DEV is already empty." >&2
   exit 1
fi

if [ "$active" = "active" ]; then
    if ! cryptsetup luksKillSlot "$DEV" "$SLT" $FRC; then
	echo "LUKSv1 slot $SLT for device $DEV couldn't be deleted"
	exit 1
    fi
else
   echo "LUKSv1 slot $SLT not present on $DEV, only LUKSMeta slot will be cleared." >&2
   if [ -z "$FRC" ]; then
       echo "The unbind operation will wipe a slot. This operation is unrecoverable." >&2
       read -r -p "Do you wish to erase LUKSMeta slot $SLT on $DEV? [ynYN] " ans < /dev/tty
       [[ "$ans" =~ ^[yY]$ ]] || exit 0
   fi
fi

if ! luksmeta wipe -f -d "$DEV" -u "$UUID" -s "$SLT"; then
    echo "LUKSMeta slot $SLT for device $DEV couldn't be deleted"
    exit 1
fi

exit 0
