#!/bin/bash

dev_flt() {
    lsblk -pPS | while read line; do
        eval "$line"
        [[ $NAME == /dev/sd* ]] && echo $NAME
    done
}


dev_part() {
    idx=$1
    shift
    for dev in $@; do
        echo $dev$idx
    done
}

mkpart_md() {

sfdisk $1 <<SFDISK
label: gpt
unit: sectors

start=   2048, size=524288, type=C12A7328-F81F-11D2-BA4B-00A0C93EC93B
start= 526336, size=524288, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4
start=1050624, type=A19D880F-05FC-4D3B-A006-743F0F84911E
SFDISK

}

mkpart_all() {
    for dev in $@; do
        mkpart_md $dev
        efibootmgr -c -d $dev -p 1 -L "Proxmox ($dev)" -l 'EFI\debian\shimx64.efi'
    done
}

devs=($(dev_flt))

mkpart_all ${devs[@]}

#TODO: hostname
mdadm -C --homehost=any -e0.9 -l1  -n${#devs[@]} --assume-clean efi  $(dev_part 1 ${devs[@]})
mdadm -C --homehost=any -e0.9 -l1  -n${#devs[@]} --assume-clean boot $(dev_part 2 ${devs[@]})
mdadm -C --homehost=any -e1.2 -l10 -n${#devs[@]} --assume-clean data $(dev_part 3 ${devs[@]})

mkfs.fat -v /dev/md/efi
mkfs.ext2 -v /dev/md/boot

cryptsetup luksFormat --type luks1 /dev/md/data
cryptsetup luksOpen /dev/md/data luks-pve

lvm pvcreate /dev/mapper/luks-pve
lvm vgcreate pve /dev/mapper/luks-pve
lvm lvcreate -L 8G -n swap pve
lvm lvcreate -L 8G -n root pve

