#!/bin/bash
set -e
set -x

#switching to root to perform chroot
if [ "$(id -u)" -ne 0 ]; then
	echo "switching from $(id -un) to root"
	exec sudo "$0" "$@"
fi

cd "$(dirname "$0")"
DIR="$(dirname "$0")"
cd ..
echo $PWD
if mountpoint -q "./outputs/chroot/proc/"; then
  umount -lf "./outputs/chroot/proc/"
fi
rm -rf './outputs/chroot'
mkdir -p ./outputs/chroot/
if mountpoint -q "./outputs/root/proc/"; then
  umount -lf "./outputs/root/proc/"
fi
rsync -a ./outputs/root/ ./outputs/chroot/
mkdir -p ./outputs/chroot/proc


mount --bind /proc ./outputs/chroot/proc
cp ./config/filesystem_chroot_install.sh ./outputs/chroot/filesystem_chroot_install.sh
cp ./config/apply_initial_host_configuration.sh ./outputs/chroot/apply_initial_host_configuration.sh
cp ./config/config.json ./outputs/chroot/config.json

#copy opensnitch rules.
echo "copying firewall rules"
rsync -a ./config/settings/opensnitch/ ./outputs/chroot/usr/src/opensnitchd/

#setup user skeleton
sudo mkdir -p ./outputs/chroot/etc/skel/.config
printf "yes" | tee ./outputs/chroot/etc/skel/.config/gnome-initial-setup-done
cp ./config/settings/skel/bash_profile ./outputs/chroot/etc/skel/.bash_profile
cp ./config/settings/skel/bashrc ./outputs/chroot/etc/skel/.bashrc
cp ./config/settings/skel/profile ./outputs/chroot/etc/skel/.profile

cp ./config/settings/skel/gnome_settings.sh ./outputs/chroot/usr/gnome_settings.sh
chmod +x ./outputs/chroot/usr/gnome_settings.sh

#installing hardened memory allocator if built
if [ -f  ./dependencies/hardened_malloc/Makefile ]; then
   rsync -a ./dependencies/hardened_malloc/ ./outputs/chroot/usr/src/hardened_malloc/
fi

cp ./config/settings/services/*.service ./outputs/chroot/etc/systemd/system/
find ./config/settings/services/ -type f -name '*.sh' -exec chmod +x {} \;
cp ./config/settings/services/*.sh ./outputs/chroot/usr/

echo "installing system from within chroot"
chmod +x ./outputs/chroot/filesystem_chroot_install.sh
chmod +x ./outputs/chroot/apply_initial_host_configuration.sh
mkdir -p ./outputs/chroot/lib/modules/

echo "installing kernel modules"
rsync -a ./dependencies/linux/modules/lib/modules/ ./outputs/chroot/lib/modules/

echo "installing filesystem"
chroot ./outputs/chroot /bin/bash -c "/filesystem_chroot_install.sh"
chroot ./outputs/chroot /bin/bash -c "/apply_initial_host_configuration.sh"
cp ./config/settings/skel/autorun.desktop ./outputs/chroot/etc/xdg/autostart/autorun.desktop

cd $DIR
cd ..
if mountpoint -q "./outputs/chroot/proc/"; then
   umount -lf "./outputs/chroot/proc/"
fi
echo 'root filesystem created.'
