#!/bin/bash

# After having had some crazy problems with loosing information regarding the
# current LUKS setup on my laptop - meaning that all boots failed and resulted
# in an error that the /dev/vgubuntu-root files was missing, I found the
# following:
#   https://askubuntu.com/questions/766048/mount-unknown-filesystem-type-lvm2-member#1078061
# For the CHRoot, things were still not up-to-par, which was resolved here:
#   https://bits.mdminhazulhaque.io/linux/chroot-with-networking-support.html
# The recipes were almost correct, but needed a few adjustments before they
# worked properly for me.

if [[ "$EUID" -ne 0 ]]; then
  echo "Please run as root"
  exit
fi

PARTITION_ROOT="/dev/nvme0n1p3"
PARTITION_BOOT="/dev/nvme0n1p2"
MOUNT_ROOT="/mnt/root"
MOUNT_PART="/dev/vgubuntu/root"

# Will ask for password
udisksctl unlock -b "${PARTITION_ROOT}"

# Mount point for CHROOT
sudo mkdir "${MOUNT_ROOT}"

# Following steps were needed to ensure that the LUKS information didn't fail,
# when trying to mount the root partition
vgdisplay
modprobe dm-mod
vgchange -ay
lvscan

#mount "${MOUNT_PART}" "${MOUNT_ROOT}"
mount -t auto -o acl "${MOUNT_PART}" "${MOUNT_ROOT}"
mount -t auto "${PARTITION_BOOT}" "${MOUNT_ROOT}/boot"
mount --bind /dev "${MOUNT_ROOT}/dev"
mount --bind /tmp "${MOUNT_ROOT}/tmp"
mount --bind /proc "${MOUNT_ROOT}/proc"
mount --bind /sys "${MOUNT_ROOT}/sys"

# do this after connecting to internet
mount --bind /etc/resolv.conf "${MOUNT_ROOT}/etc/resolv.conf"
chroot "${MOUNT_ROOT}"

echo "Please update your Debian Packages"
echo "$ apt update"
echo "Reinstall latest kernel"
echo "apt install --reinstall linux-image-generic"
echo "Fix errors occurring"
echo "User Boot-Repair to resolve Grrb problems:"
echo "See: https://help.ubuntu.com/community/Boot-Repair"
