nixfiles/extras/mk-raspberry-ext-drive.nix
2024-03-10 18:29:49 +00:00

69 lines
1.7 KiB
Nix

{
util-linux,
cryptsetup,
btrfs-progs,
writeShellApplication,
}: let
externalDriveData = import ../data/drives/raspberryExternalDrive.nix;
in
writeShellApplication {
name = "mk-raspberry-ext-drive";
runtimeInputs = [
util-linux
cryptsetup
btrfs-progs
];
text = ''
if [ -z "''${1-}" ]; then
echo "Please specify a path to device as first argument"
exit 1
fi
DRIVE_PATH=$1
if [ -z "''${2-}" ]; then
echo "Please specify a key file to use"
exit 1
fi
KEY_FILE=$2
if [ -z "''${3-}" ]; then
echo "Please specify a temp mountpoint to use"
exit 1
fi
TEMP_MOUNTPOINT=$3
if [ "$EUID" -ne 0 ]; then
echo "Please run as root"
exit
fi
echo "Wiping Partitions..."
wipefs --all "$DRIVE_PATH"
echo "Creating Encrypted Partition"
cryptsetup luksFormat "$DRIVE_PATH" --key-file "$KEY_FILE" --label "${externalDriveData.encryptedLabel}"
echo "Opening Encrypted Partition"
cryptsetup open "$DRIVE_PATH" "mk-raspberry-ext-drive" --key-file "$KEY_FILE"
echo "Formatting Encrypted Filesystem"
mkfs.btrfs -L "${externalDriveData.unencryptedLabel}" /dev/mapper/mk-raspberry-ext-drive
echo "Mounting Partition"
mount -t btrfs /dev/mapper/mk-raspberry-ext-drive "$TEMP_MOUNTPOINT"
echo "Creating Folders"
mkdir "$TEMP_MOUNTPOINT/backups"
mkdir "$TEMP_MOUNTPOINT/storage"
mkdir "$TEMP_MOUNTPOINT/extras"
echo "Unmounting"
umount "$TEMP_MOUNTPOINT"
echo "Closing mapper device"
cryptsetup close "mk-raspberry-ext-drive"
'';
}