#!/usr/bin/env bash

# Mount on linux
# Lsblk

lsblk
# read device name from user input and choose default value of sdb1
read -p "Enter device name (default: sdb1): " device
# if user input is empty, set device to sdb1
device=${device:-sdb1}
read -p "Enter mount name (default: mymnt): " mnt_name
mnt_name=${mnt_name:-mymnt}
sudo mkdir -p /media/$mnt_name  # Make sure to create the mounting directory.

# check if drive is bitlocker encrypted then print encryption type else print not encrypted
if ! command -v dislocker &> /dev/null
then
    echo "dislocker could not be found"
    echo "Installing dislocker"
    sudo apt install dislocker
fi


# bitlocker_status=$(sudo bash -c "ls /sys/class/block/$(basename $device)/holders/ | grep -o bitlocker")
bitlocker_status=$(lsblk -o FSTYPE "/dev/$device" | grep -o BitLocker)

if [ "$bitlocker_status" = "BitLocker" ];  then
    echo ">>>>>> Drive is bitlocker encrypted, therefore, bitlocker is needded"
    # If drive is bitlocker , following: https://www.linuxuprising.com/2019/04/how-to-mount-bitlocker-encrypted.html

    # check if password is stored here: $HOME/dotfiles/creds/data/bitlocker_pwd if so, read it.
    # if not, prompt user for password and store it in the file.
    if [ -f "$HOME/dotfiles/creds/data/bitlocker_pwd" ]; then
        echo ">>>>>> Bitlocker Password file detected at default location $HOME/dotfiles/creds/data/bitlocker_pwd"
        bitlocker_pwd=$(cat $HOME/dotfiles/creds/data/bitlocker_pwd)
    else
        echo ">>>>>> Password file does not exist"
        read -p "Enter bitlocker password: " bitlocker_pwd
        echo $bitlocker_pwd > $HOME/dotfiles/creds/data/bitlocker_pwd
    fi


    sudo mkdir -p /media/$mnt_name"_bitlocker"
    sudo dislocker /dev/$device -u -- /media/$mnt_name"_bitlocker" # Will be prompted for password (-u)
    # sudo mount -o loop /media/bitlocker/dislocker-file /media/bitlockermount
    # Modified from here to fix permissions: https://askubuntu.com/questions/1045057/i-cant-write-only-read-on-usb-device-encrypted-with-bitlocker
    sudo mount -o loop,rw,uid=1000,gid=1000 /media/$mnt_name"_bitlocker"/dislocker-file /media/$mnt_name
else
    echo "Drive is not encrypted"
    sudo mount --source /dev/$device --target /media/$mnt_name
fi

# echo a success message if mount was successful (last command) else print error message
if [ $? -eq 0 ]; then
    echo "The drive has been successfully mounted at /media/$mnt_name"
    echo "--------------------------------------"
else
    echo "There was an error while mounting the drive. Please check your input and try again."
    exit 1
fi

# https://askubuntu.com/questions/1059228/how-to-mount-a-usb-drive-in-ubuntu-18-04
