#!/bin/sh -e

exec 2>> /tmp/`basename ${0}`.log
set -x

PRESEED_FILE="`mktemp`"
GET="/bin/debconf-get"
DISKDEVICE="`${GET} preseed/diskdevice`"
VG="vg_`uname -n`"
if "${GET}" partman-crypto/passphrase; then
  METHOD="crypto"
  RECIPE="boot-crypto"
else
  METHOD="lvm"
  RECIPE="boot-root"
fi

cat > "${PRESEED_FILE}" << END_OF_PRESEED
# http://serverfault.com/q/674137/
# preeseding-a-debian-stable-install-with-a-complex-partitioning-scheme-missing
# https://www.bishnet.net/tim/blog/2015/01/29/understanding-partman-autoexpert_recipe/

d-i grub-installer/only_debian boolean false
d-i grub-installer/bootdev string ${DISKDEVICE}

d-i partman/choose_partition \
      select Finish partitioning and write changes to disk
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true
d-i partman/default_filesystem string ext2

d-i partman-auto/disk string ${DISKDEVICE}
d-i partman-auto/purge_lvm_from_device boolean true
d-i partman-auto/method string ${METHOD}
d-i partman-auto/choose_recipe select ${RECIPE}
d-i partman-auto-lvm/guided_size string max
d-i partman-auto-lvm/new_vg_name string ${VG}
d-i partman-auto/expert_recipe string ${RECIPE} :: \
        `"${GET}" preseed/partition_boot_sizes` \
        ext2 \$primary{ } \$bootable{ } \
        method{ format } format{ } \
        use_filesystem{ } filesystem{ ext2 } \
        mountpoint{ /boot } \
        .\
        `"${GET}" preseed/partition_root_sizes` \
        ext2 \$lvmok{ } lv_name{ root } \
        in_vg { ${VG} } method{ format } format{ } \
        use_filesystem{ } filesystem{ ext2 } mountpoint{ / } \
        .\
        `"${GET}" preseed/partition_swap_sizes` \
        linux-swap \$lvmok{ } lv_name{ swap } \
        in_vg { ${VG} } method{ swap } format{ } \
        .\
        `"${GET}" preseed/partition_unused_sizes` \
        ext2 \$lvmok{ } lv_name{ unused } \
        in_vg { ${VG} } method{ keep } format{ } \
        use_filesystem{ } filesystem{ } mountpoint{ } \
        .

#d-i partman-crypto/confirm_nooverwrite boolean true
d-i partman-crypto/erase_data boolean no

d-i partman-lvm/confirm boolean true
d-i partman-lvm/confirm_nooverwrite boolean true
d-i partman-lvm/device_remove_lvm boolean true

d-i partman-md/device_remove_md boolean true
d-i partman-md/device_remove_md boolean true

d-i partman-partitioning/confirm_write_new_label boolean true
END_OF_PRESEED
/bin/debconf-set-selections "${PRESEED_FILE}"

SKIP_ERASE="/tmp/apply-skip_erase-patch.sh"
cat > "${SKIP_ERASE}" << "END_OF_SCRIPT"
#!/bin/sh -e
# https://www.linuxjournal.com/content/preseeding-full-disk-encryption
# https://gitlab.com/cryptsetup/cryptsetup/-/wikis/FrequentlyAskedQuestions#5-security-aspects (5.3)

sed -i.bak 's/-f $id\/skip_erase/-d $id/g' /lib/partman/lib/crypto-base.sh
END_OF_SCRIPT
chmod +x "${SKIP_ERASE}"
