#!/usr/bin/env bash
# add automate scripts
#git clone http://git.devuan.org/cyteen/automate

cd automate

# Add contrib to sources.list
bash 001_apt-sources.sh

# Add zfs
bash 010_zfs.sh

# Mount the hdd
ZFS_HOME=/mnt
zpool import -a -R ${ZFS_HOME}

mkdir -p ${ZFS_HOME}/dev
mount -o bind /dev ${ZFS_HOME}/dev
mkdir -p ${ZFS_HOME}/dev/pts
mount -o bind /dev/pts ${ZFS_HOME}/dev/pts
mkdir -p ${ZFS_HOME}/sys
mount -o bind /sys ${ZFS_HOME}/sys
mkdir -p ${ZFS_HOME}/proc
mount -t proc /proc ${ZFS_HOME}/proc
mkdir -p ${ZFS_HOME}/run
mount -o bind /run ${ZFS_HOME}/run

chroot ${ZFS_HOME} bash -c 'apt install -y --reinstall dkms spl-dkms gcc-6 libc6-dev debhelper dh-autoreconf linux-headers-4.9.0-4-all-amd64' 

chroot ${ZFS_HOME} bash -c 'apt install -y --reinstall zfs-dkms zfs-initramfs zfsnap zfsutils-linux busybox'

chroot ${ZFS_HOME} bash -c "cat > /usr/share/initramfs-tools/conf.d/zfs" << 'EOF'
for x in $(cat /proc/cmdline)
do
    case $x in
        root=ZFS=*)
            BOOT=zfs
            ;;
    esac
done
EOF

#chroot ${ZFS_HOME} dpkg-reconfigure zfs-dkms

chroot ${ZFS_HOME} ls /var/lib/initramfs-tools | sudo xargs -n1 /usr/lib/dkms/dkms_autoinstaller start

chroot ${ZFS_HOME} bash -c 'apt -y -f install'

# Rebuild drivers
#chroot ${ZFS_HOME} dpkg-reconfigure spl-dkms
#chroot ${ZFS_HOME} dpkg-reconfigure zfs-dkms

# Update initramfs
# Error: live system without live media mounted as /lib/live/mount/medium
chroot ${ZFS_HOME} bash -c 'apt remove -y live-tools'
chroot ${ZFS_HOME} bash -c 'apt install -y initramfs-tools'
chroot ${ZFS_HOME} bash -c 'update-initramfs -v -u -t -k all'

# Update grub menu
chroot ${ZFS_HOME} grub-mkdevicemap 
chroot ${ZFS_HOME} grub-probe /
chroot ${ZFS_HOME} update-grub

chroot ${ZFS_HOME} lsinitramfs /boot/initrd.img-*

umount -lf ${ZFS_HOME}/dev/pts
umount -lf ${ZFS_HOME}/dev
umount -lf ${ZFS_HOME}/sys
umount -lf ${ZFS_HOME}/proc
umount -lf ${ZFS_HOME}/run
umount -lf ${ZFS_HOME}
