#!/bin/sh

# Fail if any command fails
set -e

#Constants
FDISK_INPUT_FILE="./fdisk_inputs"
MOUNT_POINT="/media"
MAP_POINT="/dev/mapper"
TEMP_KEY_FILE="/tmp/encryption_key"
SECRET_DIR="secret/log-encryption"
VAULT_ADDR="https://vault.zooxlabs.com:8200"

# Request ID of drive to format
echo "Please enter the slot of the drive to format (ex. /dev/sdb):"
read device

# Warn user
echo "Only proceed if you are sure that $device is the desired drive to format!!! (Enter to continue)"
read _

# Format disk input
sudo fdisk "$device" < "$FDISK_INPUT_FILE"

# Enter Label for Disk
echo "Please enter the drive number (ex. zooxusb-60 label means enter '60')"
read device_number

# Partition Labels
CRYPT_LABEL="zooxcrypt-$device_number"
USB_LABEL="zooxusb-$device_number"

# Create new credentials for robot
UUID=$(uuid)
ENCRYPTION_KEY=$(openssl rand 16)
BASE64_KEY="$(echo $ENCRYPTION_KEY | base64)"

echo -n "$ENCRYPTION_KEY" > "$TEMP_KEY_FILE"

# Write key to vault
echo "Please enter LDAP credentials:"
VAULT_ADDR="$VAULT_ADDR" vault login --method=ldap username=$(whoami)
VAULT_ADDR="$VAULT_ADDR" vault write "$SECRET_DIR/$USB_LABEL/$UUID" "encryption_key=$BASE64_KEY"
VAULT_ADDR="$VAULT_ADDR" vault write "$SECRET_DIR/$USB_LABEL/latest" "encryption_key=$BASE64_KEY"

# Encrypt second partition
echo "Only proceed if you are confident that you are encrypting the right device (ex. /dev/sdb2)!!!!"
sudo cryptsetup luksFormat --key-file "$TEMP_KEY_FILE" "${device}2"

# Mount encrypted drive
sudo cryptsetup luksOpen --key-file "$TEMP_KEY_FILE" "${device}2" "$USB_LABEL"
sudo mkfs.ext4 "$MAP_POINT/$USB_LABEL"
sudo e2label "$MAP_POINT/$USB_LABEL" "$USB_LABEL"
sudo cryptsetup luksClose "$MAP_POINT/$USB_LABEL"

# Remove key file
rm "$TEMP_KEY_FILE"

# Mount metadata partition
sudo mkdir -p "$MOUNT_POINT/$CRYPT_LABEL"
sudo mkfs.ext4 "${device}1"
sudo e2label "${device}1" "$CRYPT_LABEL"
sudo mount "${device}1" "$MOUNT_POINT/$CRYPT_LABEL"
sudo chown -R "$(whoami)" "$MOUNT_POINT/$CRYPT_LABEL"

# Add relevant files
echo -n "$CRYPT_LABEL" > "$MOUNT_POINT/$CRYPT_LABEL/label"
echo -n "$UUID" > "$MOUNT_POINT/$CRYPT_LABEL/uuid"

# Unmount metadata partition
sudo umount "${device}1"
sudo rmdir "$MOUNT_POINT/$CRYPT_LABEL"
