#!/bin/bash
set -ex
set -o pipefail

# mount keyfile
losetup /dev/loop0 crypt_keyfile
cryptsetup luksOpen /dev/loop0 crypt_keyfile
mount /dev/mapper/crypt_keyfile /tmp/crypt_keyfile
keyfile=/tmp/crypt_keyfile/keyfile

finally() {
  # always try to run all of those
  umount /tmp/crypt_keyfile || true
  cryptsetup luksClose crypt_keyfile || true
  losetup -d /dev/loop0 || true
  exit 1
}
trap finally SIGINT EXIT

luks_open() {
  device=$1
  name=$2
  [[ -b $device ]] && sudo cryptsetup luksOpen --key-file $keyfile $device $name
}
luks_open /dev/md0 crypt0
luks_open /dev/md1 crypt1 || luks_open /dev/md127 crypt1

# wait until block device is available
while [[ ! -b /dev/raid/storage ]]; do
  echo -n '.'
  sleep 0.25
done
echo
sudo mount /dev/raid/storage /media/storage
ls /media/storage
