#!/bin/bash

baseDir=$(pwd)

build=$baseDir/build

config=$baseDir/config

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

pack_list=(live cli disk net firmware dm-common xfce4 cinnamon gui libreoffice vm)

declare -A pack_name
pack_name[dm-common]="Composant commun pour l' interface graphique"
pack_name[xfce4]="Environnement de bureau Xfce"
pack_name[cinnamon]="Environnement de bureau Cinnamon"
pack_name[gui]="Ensemble de logiciel graphique"
pack_name[libreoffice]="Libreoffice Writer et Calc"
pack_name[vm]="Driver Virtualisation"

pack_forced=(live cli disk net firmware)

pack_default=(dm-common xfce4 gui vm)

_usage()
{
	cat <<EOF
-d use default pack
-v Specifie Debian codename
-o Specifie output folder
-i if set create iso instead of only squashfs
EOF
}

if [ -z "$1" ]
then
	_usage
	exit 1
fi

#export http_proxy="http://192.168.110.1:3142"

KERNEL_PARAM="boot=live components lang=fr_FR.UTF-8 locales=fr_FR.UTF-8 keyboard-layouts=fr keyboard-model=pc105 timezone=Europe/Paris utc=yes"

_check()
{

	if [ -z "$out" ]
	then
		printf "\e[31mPlease specifie output folder\e[0m\n"
		_usage
		exit 1
	fi

	if [ -z "$debian_version" ]
	then
		printf "\e[31mPlease specifie Debian codename\e[0m\n"
		_usage
		exit 1
	fi

	if [ -d "$out" ]
	then
		printf "Write in \e[96m$out\e[0m folder\n"
		if [ "$(ls -A $out)" ]
		then
			printf "\e[91m$out is not empty be careful\e[0m\n"
		fi
	else
		printf "\e[31m$out is not a folder\e[0m\n"
		_usage
		exit 1
	fi

	printf "Debian version of live system: \e[96m$debian_version\e[0m\n"

}

_choose()
{
	declare -a checklist
	size=$((${#pack_list[@]}-(${#pack_forced[@]})))
	for pack in ${pack_list[@]}; do
		[[  "${pack_forced[*]}" =~ "$pack" ]] && continue
		[[  "${pack_default[*]}" =~ "$pack" ]] && status="ON" || status="OFF"

		checklist+=($pack "${pack_name[$pack]}" $status)
	done

	RESULT=$(whiptail --title "Make debian live system" --checklist "Select pack list" 15 70 ${size} "${checklist[@]}" 3>&1 1>&2 2>&3 | xargs)

	pack=("${pack_forced[@]} ${RESULT[@]}")

	printf "Pack list: \e[96m${pack[*]}\e[0m\n"

	read -p "Continue ? " -n 1 -r
	echo
	if ! [[ $REPLY =~ ^[YyOo]$ ]]
	then
		echo "Cancel"
		exit
	fi
}

_config()
{

	mkdir -p $build/config

	cd $build

	ln -sr $config/includes.chroot $build/config
	ln -sr $config/packages.chroot $build/config

	mkdir -p $build/config/hooks
	ln -sr $config/hooks/live $build/config/hooks

	lb clean
	lb clean --cache

	#--apt-http-proxy "http://192.168.110.1:3142" \
	lb config noauto \
	--architectures amd64 \
	--distribution $debian_version \
	--binary-images iso-hybrid \
	--archive-areas "main contrib non-free" \
	--debian-installer none \
	--apt-recommends false \
	--updates true \
	--security true \
	--source false \
	--backports false \
	--memtest none \
	--bootappend-live "$KERNEL_PARAM"

	rm $build/config/package-lists/*

	for file in ${pack[@]}; do
		ln -sr $config/package-lists/$file.list.chroot $build/config/package-lists/$file.list.chroot
	done

}

_build()
{
	
	printf "\e[96mBootstrap new root filesystem\e[0m\n"
	lb bootstrap

	printf "\e[96mBuild live OS file system\e[0m\n"
	lb chroot

	# Write commit hash and build date
	echo "$(git -C $baseDir log -1 --pretty='%cd %h %s' --date=format:"%F")" >> $build/chroot/etc/debian_version

}

_create_squashfs()
{

	printf "\e[96mPreparing root filesystem\e[0m\n"
	lb binary_chroot

	# Chroot preparation component lists
	# We deliberately exclude 'debianchroot'
	CHROOT_PREP_MOUNTS="devpts proc selinuxfs sysfs"
	CHROOT_PREP_OTHER="dpkg tmpfs sysv-rc hosts resolv hostname apt"

	# Configuring chroot
	lb chroot_prep install "${CHROOT_PREP_MOUNTS}"
	lb chroot_prep install "${CHROOT_PREP_OTHER}" mode-apt-install-binary mode-archives-chroot
	lb chroot_archives chroot install

	printf "\e[96mBuilding root filesystem\e[0m\n"
	lb binary_rootfs

	printf "\e[96mPrepare images\e[0m\n"
	lb binary_linux-image
	lb binary_syslinux

	# Deconfiguring chroot
	lb chroot_prep remove "${CHROOT_PREP_MOUNTS}"
	lb chroot_prep remove "${CHROOT_PREP_OTHER}"

	printf "\e[96mCopy filesystem\e[0m\n"

	cp $build/binary/live/{initrd.img,vmlinuz,filesystem.squashfs} $out/

	chown $SUDO_UID:$SUDO_GID $out/{initrd.img,vmlinuz,filesystem.squashfs}

}

_create_iso()
{

	printf "\e[96mBuild binary (live disc) images\e[0m\n"
	lb binary

	printf "\e[96mCopy ISO\e[0m\n"

	if [ -d "$out" ]
	then
		$out="$out/live-${debian_version}-image.iso"
	fi

	cp $build/live-image-amd64.hybrid.iso $out

	chown $SUDO_UID:$SUDO_GID $out

}
_delete()
{
	printf "\e[96mDelete $build\e[0m\n"
	rm -r $build
}

while getopts "dv:o:i" OPTION; do
	case $OPTION in
	d)
		default=true
		;;
	v)
		debian_version=${OPTARG}
		;;
	o)
		out="$(realpath ${OPTARG})"
		;;
	i)
		iso=true
		;;
	*)
		_usage
		exit 1
		;;
	esac
done

_check
[[ $default = true ]] && pack=("${pack_forced[@]} ${pack_default[@]}") || _choose
_config
_build

mkdir -p $build/chroot/etc/skel/.ssh
cp -v /home/lionel/.ssh/{config,key_rsa_majalis,key_rsa_majalis.pub} $build/chroot/etc/skel/.ssh
sudo -u $SUDO_USER ssh-keygen -H -F netdldata.net > $build/chroot/etc/skel/.ssh/known_hosts

[[ $iso = true ]] && _create_iso || _create_squashfs

_delete
