#!/bin/bash
# -*- coding: utf-8 -*-
#
#   Copyright 2022, Torsten Wohlfarth <two@tuxedocomputers.com>
#
#   This module is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This module is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this module. If not, see <http://www.gnu.org/licenses/>.

CHROOT=$(mount | grep proc | grep calamares | awk '{print $3}' | sed -e "s#/proc##g")

sysid=""
bootid=""
cryptid=""
cryptdev=""
efiid=""
swapid=""
sysid=$(lsblk -l -o NAME,UUID,LABEL,FSTYPE | awk '/system-root/{ print $2}')
bootid=$(lsblk --fs | grep -B 5 system-root | awk '/BOOT/{ print $5}')
cryptid=$(lsblk -s -l -o NAME,UUID,LABEL,FSTYPE | grep -B 3 system-root | awk '/LUKS/{ print $2 }')
cryptdev=$(lsblk -s -l -o NAME,UUID,LABEL,FSTYPE | grep -B 3 system-root | awk '/LVM/{ print $1 }')
efiid=$(lsblk --fs | grep -B 5 system-root | awk '/EFI/{ print $5}')
swapid=$(lsblk -l -o NAME,UUID,LABEL,FSTYPE | awk '/system-swap/{ print $2}')
rm -f /etc/sudoers.d/15*
printf "UUID=$bootid                /boot           ext3            defaults,noatime        0  2\n" > /etc/fstab
printf "UUID=$efiid                 /boot/efi       vfat            umask=007               0  0\n" >> /etc/fstab
printf "UUID=$sysid         /               ext4            defaults,noatime        0  1\n" >> /etc/fstab
printf "UUID=$swapid                none            swap            sw              0  0\n" >> /etc/fstab
printf "$cryptdev		UUID="$cryptid"		none    luks,discard\n" > /etc/crypttab

cleanup() {
update-initramfs -c -k all
update-grub
/sbin/grub-install --no-uefi-secure-boot --bootloader-id tuxedo-fallback
/sbin/grub-install --bootloader-id tuxedo
if [ -d /boot/efi ]; then
    if [ ! -f /boot/efi/EFI/ubuntu/grub.cfg 2>/dev/null ]; then
	mkdir -p /boot/efi/EFI/ubuntu
	cp -af /boot/efi/EFI/tuxedo/grub.cfg /boot/efi/EFI/ubuntu/grub.cfg
    fi
fi
dpkg-reconfigure -f noninteractive keyboard-configuration
apt-get -y purge *calamares* --autoremove
}

cleanup 
#| zenity --progress --title="Working ..." --text="generate initrd for installed system" --pulsate --no-cancel --width=400 --auto-close
exit 0
