#!/bin/bash
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <keyserver>" "<image>" "<device>"
    exit 1
fi

KEYSERVER=$1
IMAGE=$2
DEVICE=$3

if [ ! -e $IMAGE ]; then
    logger "open_volume: ($DEVICE) Image file not found"
    exit 1
fi

# if keyserver is not reachable, exit
if ! curl -s -I $KEYSERVER > /dev/null; then
    logger "open_volume: ($DEVICE) Key server not reachable, exiting."
    exit 1
fi

# If device is already open, exit
if [ -e /dev/mapper/$DEVICE ]; then
    echo "open_volume: ($DEVICE) Device already open, exiting."
    exit 1
fi

uuid=$(cat /proc/cpuinfo | grep 'model name' | head -1)
uuid+=$(ip link show eth0 | grep ether | awk '{print $2}')
uuid+=$(sudo dmidecode -s system-uuid)
KEYID=$(echo -n "$uuid" | md5sum | awk '{print $1}')

logger "open_volume: ($DEVICE) Downloading key from key server,"
LOCALKEYFILE=$(mktemp)
curl -s -o $LOCALKEYFILE $KEYSERVER/$KEYID
if [ $? -ne 0 ]; then
    logger "open_volume: ($DEVICE) Failed to download key from key server"
    rm $LOCALKEYFILE
    exit 1
fi
logger "open_volume:'$DEVICE' Key downloaded successfully, opening volume"
/usr/sbin/cryptsetup luksOpen $IMAGE $DEVICE -d $LOCALKEYFILE
if [ $? -ne 0 ]; then
    logger "open_volume: ($DEVICE) Failed to open volume"
    rm $LOCALKEYFILE
    exit 1
fi
logger "open_volume: ($DEVICE) Volume opened successfully, removing key file"
rm $LOCALKEYFILE
exit 0