#!/bin/bash

set -e
set -x

dist='https://repo.rumyantsev.com/images/debian12-mdraid-lvm-uefi.tgz'

blkid /dev/pve/root || mkfs.ext4 /dev/pve/root
blkid /dev/pve/swap || mkswap /dev/pve/swap

[ -d /target ] || mkdir -p /target
grep -F ' /target ' /proc/mounts || mount /dev/pve/root /target

[ -d /target/boot ] || mkdir -p /target/boot
grep -F ' /target/boot ' /proc/mounts || mount /dev/md/boot /target/boot

[ -d /target/boot/efi ] || mkdir -p /target/boot/efi
grep -F ' /target/boot/efi ' /proc/mounts || mount /dev/md/efi /target/boot/efi

[ -f /target/etc/debian_version ] || curl -k $dist | tar -xzvC /target

grep -F ' /target/dev ' /proc/mounts     || mount -o bind   /dev   /target/dev
grep -F ' /target/run ' /proc/mounts     || mount -o bind   /run   /target/run
grep -F ' /target/dev/pts ' /proc/mounts || mount -t devpts devpts /target/dev/pts
grep -F ' /target/dev/shm ' /proc/mounts || mount -t tmpfs  shm    /target/dev/shm
grep -F ' /target/sys ' /proc/mounts     || mount -t sysfs  sys    /target/sys
grep -F ' /target/proc ' /proc/mounts    || mount -t proc   proc   /target/proc

/bin/sed -i -e '/^ARRAY/,$d' /target/etc/mdadm/mdadm.conf
/sbin/mdadm --detail --scan >> /target/etc/mdadm/mdadm.conf
eval $(/sbin/blkid -o export /dev/md/data)
echo "luks-pve UUID=$UUID none luks" > /target/etc/crypttab

echo 'nameserver 8.8.8.8' > /target/etc/resolv.conf
chroot /target bash -c 'export PATH=/usr/bin:/usr/sbin; apt update; apt install cryptsetup-initramfs ifenslave bridge-utils'
chroot /target bash -c 'export PATH=/usr/bin:/usr/sbin; update-initramfs -u; update-grub'

eval $(/sbin/mdadm --detail -Y /dev/md/boot)
eval $(/sbin/blkid -o export /dev/md/boot)
BOOT_UUID=$UUID
eval $(/sbin/blkid -o export /dev/md/efi)
EFI_UUID=$UUID

search="search.fs_uuid ${BOOT_UUID} root mduuid/${MD_UUID//:/}"
sed -i -e "s|^search.*|${search}|" /target/boot/efi/EFI/debian/grub.cfg

/bin/sed -i -e '/^UUID/d' /target/etc/fstab
echo "
UUID=${BOOT_UUID} /boot ext2 defaults 0 2
UUID=${EFI_UUID} /boot/efi vfat umask=0077 0 1
" >> /target/etc/fstab

chroot /target bash -c 'LVM_SUPPRESS_FD_WARNINGS=1 update-grub'
chroot /target bash -c 'rm -v /etc/ssh/ssh_host_*; dpkg-reconfigure openssh-server'

umount /target/boot/efi
umount /target/boot
umount /target/dev/pts
umount /target/dev/shm
umount /target/dev
umount /target/proc
umount /target/run
umount /target/sys
umount /target
