#!/bin/bash

devbase="crypt_storage_"
declare -A disks=(
    [ata-TOSHIBA_MG10ACA20TE_Y2W0A0EWF4MJ-part1]=d1
    [ata-TOSHIBA_MG10ACA20TE_Y2W0A0NVF4MJ-part1]=d2
    [ata-TOSHIBA_MG10ACA20TE_Y2W0A0ACF4MJ-part1]=d3
    [ata-TOSHIBA_MG10ACA20TE_X3C0A2S0F4MJ-part1]=d4
)

die () {
    echo "$1"
    exit 1
}

#pwd="$(yourscript that returns crypt key)"
pwd=""
if [[ -z "$pwd" ]]; then
    echo -n "Decryption key? "
    stty -echo 2>/dev/null
    read -r pwd
    stty echo 2>/dev/null
    echo
fi

[[ -z "$pwd" ]] && die "Didn't get a decryption key."

echo "Decrypting devices."
for disk in "${!disks[@]}"; do
    echo "$pwd" | cryptsetup luksOpen /dev/disk/by-id/"$disk" "$devbase${disks[$disk]}" || die "Couldn't decrypt $disk"
done
echo "Finished decrypting devices."

echo "Mounting devices."

for disk in "${!disks[@]}"; do
    mount_point="/mnt/${disks[$disk]}"
    mount "/dev/mapper/$devbase${disks[$disk]}" "$mount_point" || die "Couldn't mount $disk at $mount_point"
    if [[ ${disks[$disk]} =~ ^d ]]; then
        mount -o space_cache=v2,noatime,subvol=.snapshots "/dev/mapper/$devbase${disks[$disk]}" "/mnt/${disks[$disk]}/.snapshots"
        mount -o space_cache=v2,noatime,subvol=.snapraid "/dev/mapper/$devbase${disks[$disk]}" "/mnt/${disks[$disk]}/.snapraid"
    fi
done

echo "All devices and subvolumes mounted successfully."
