#!/bin/bash -e

disk="$1"
pv=pv00
vg=vg00

if test ! -b "$1"; then
    echo usage: $0 blockdevice
    exit 1
fi

function partition() {
	disk="$1"
	num="$2"
	case ${disk} in
		*[[:digit:]])
			echo ${disk}p${num}
			;;
		*)
			echo ${disk}${num}
			;;
	esac
}

parted -s -- ${disk} mklabel msdos
parted -s -- ${disk} mkpart primary 2048s 256MiB
parted -s -- ${disk} mkpart primary 256MiB -1s
parted -s -- ${disk} unit MiB print
partprobe
part1=$(partition ${disk} 1)
part2=$(partition ${disk} 2)

mkfs -t ext4 -L xboot ${part1}

echo "secret" >/tmp/password
cryptsetup -q luksFormat ${part2} /tmp/password
cryptsetup -d /tmp/password luksOpen ${part2} ${pv}
rm /tmp/password
crypt_uuid=$(cryptsetup luksUUID ${part2})
crypttab="${pv} UUID=$crypt_uuid none luks"
partprobe

pvcreate /dev/mapper/${pv}
vgcreate ${vg} /dev/mapper/${pv}

lvcreate --size 1G --name xroot ${vg}
lvcreate --extents 100%FREE --name xexport ${vg}
partprobe
mkfs -t ext4 -L xroot -U $(uuidgen) /dev/${vg}/xroot
mkfs -t ext4 -L xexport -U $(uuidgen) /dev/${vg}/xexport
partprobe
echo ls -al /dev/disk/by-uuid
ls -al /dev/disk/by-uuid
echo ls -al /dev/mapper
ls -al /dev/mapper
echo "blkid -c /dev/null | sort"
blkid -c /dev/null | sort

vgchange -an ${vg}
cryptsetup luksClose ${pv}
