#!/usr/bin/env zsh
# Copyright (c) 2017 Dyne.org Foundation
# live-sdk is written and maintained by Ivan J. <parazyd@dyne.org>
#
# This file is part of live-sdk
# devuan-desktop-live.blend is maintained by fsmithred
#
# This source code 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 software 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 source code. If not, see <http://www.gnu.org/licenses/>.

BLENDPATH="${BLENDPATH:-$(dirname $0)}"

source $BLENDPATH/config
source $BLENDPATH/helpers
source $BLENDPATH/sysconf

blend_release_path=$BLENDPATH/$release
blend_packages=${blend_release_path}/packages
blend_scripts=${blend_release_path}/scripts

blend_preinst() {
	fn blend_preinst
	req=(blend_name username userpass)
	ckreq || return 1

	notice "executing $blend_name preinst"
	if [[ -d "${blend_scripts}" ]]; then
		notice "copying blend-specific scripts into $R/extra/custom-scripts"
		mkdir -p "$R/extra/custom-scripts" || { zerr; return 1; }
		cp -fv "$blend_scripts"/*.sh "$R/extra/custom-scripts"
	else
		notice "no blend-specific scripts found in ${blend_scripts}"
	fi

	if [[ -d "${blend_scripts}" ]]; then
		notice "copying blend-specific scripts"
		mkdir -p "$R/extra/custom-scripts"
		cp -fv "$blend_scripts"/*.sh "$R/extra/custom-scripts"
	else
		notice "no blend-specific scripts found in ${blend_release_path}/automate"
	fi

	enable_apt-proxy

	notice "get selections for current system. DISABLED"
	# Either run here or look at the get_selections function 
	# in ${blends_release_path}/../helpers and run on the
	# system you wish to duplicate.
	#
	#get_selections

	# For packages in a separate debs directory
	notice "blend-specific packages."
	if [[ -d "${blend_packages}" ]] ; then
		act "copying blend-specific debs from ${blend_packages} into $R/extra/custom-packages"
		mkdir -p "$R/extra/custom-packages" || { zerr; return 1; }
		cp -fv "$blend_packages"/*.deb "$R/extra/custom-packages"
	else 
		notice "no blend-specific debs found in ${blend_packages}"
	fi

	# for packages in the top level blend path.
	setopt EXTENDED_GLOB
	if [[ -n $blend_release_path/"*.deb"(#qN) ]]; then 
		act "copying blend-specific debs from ${blend_release_path} into $R/extra/custom-packages"
		mkdir -p "$strapdir/extra/custom-packages" || { zerr; return 1; }
		cp -fv "$blend_release_path"/*.deb "$R/extra/custom-packages" || { zerr; return 1; }
	else
		print "No debian packages found in ${blend_release_path}."
	fi

	cat <<-EOF | sudo tee "$strapdir/install-custompackages" >/dev/null
		#!/bin/sh
		cd extra_packages
		dpkg -i *_all.deb *_${arch}.deb
		apt-get -f install
		cd - >/dev/null
		rm -rf extra_packages
	EOF

	act "installing blend-specific packages."
	chroot-script -d install-custompackages || { zerr; return 1; }

	notice "adding user account."
	
	act "create default user."
        add-user 
}

blend_postinst() {
	fn blend_postinst
	req=(strapdir blend_name)
	ckreq || return 1

	notice "executing $blend_name postinst"

	act "install rootfs-overlay"
	pushd "$strapdir"
		sudo rsync -avx --no-o --no-g "$blend_release_path"/rootfs-overlay/* . || zerr
	popd

	#act "enable apt proxy."
	#enable_apt-proxy

	act "install kernel headers"
	install_kernel_headers

	act "install zfs"
	install_zfs

	act "install bootloader"
	if [[ ${arch} == 'arm64' ]]; then
		install_u-boot
	else
		install_grub
	fi


	act "set selections."
	if [[ -f ${strapdir}/var/tmp/packages.list ]]; then
		set_selections
	fi

	blend_finalize || zerr

	#act "disable apt proxy."
	#disable_apt-proxy

	act "Unmount partitions and export zfs pools." 
	# The zpool command will refuse to import any storage pools that have not been exported."
	image_zfs_umount || zerr
}

blend_finalize() {
	fn blend_finalize
	req=(strapdir username userpass default_shell grub_theme)
	ckreq || return 1

	notice "Finalizing."

	# act "enabling ssh."
	# enablessh
	
	act "create /etc/fstab"
	pushd "${strapdir}"
	touch /etc/fstab
	printf 'none\t\t\t\t\t\t\t\t/sys/kernel/debug\tdebugfs\tdefaults\t0 0\n' >> ./etc/fstab
	printf 'bpool/BOOT/devuan-1\t\t\t\t\t\t/boot\t\t\tzfs\tnodev,relatime\t0 0\n' >> ./etc/fstab
	printf 'none\t\t\t\t\t\t\t\t/sys/fs/cgroup\t\tcgroup\tdefaults\t0 0\n' >> ./etc/fstab

	printf "${disk_path}/${disk_name}-part${efi_part_number}\t${grub_mount}\t\tvfat\tumask=0077\t0 1\n" >> ./etc/fstab
	popd

	act "set grub theme."
	pushd "$strapdir"
	# This line is in desktop-base so we should always have a grub theme in /etc/default/grub to change..
	# printf "\nGRUB_THEME=/usr/share/desktop-base/grub-themes/${grub_theme}/theme.txt\n" >> /etc/default/grub
	grub_theme_path="/usr/share/desktop-base/grub-themes/${grub_theme}/theme.txt"
	regex="s|^\(GRUB_THEME=\).*|\1\"${grub_theme_path}\"|"
	sed -i "${regex}" ./etc/default/grub
	popd

	act "add swap partitions to fstab"
	pushd "${strapdir}"
	for swap_partition in "${swap_partitions[@]}"; do
		printf "${swap_partition}\tnone\t\t\tswap\tdefaults\t0 0\n" >> ./etc/fstab
	done

	#printf "/dev/zvol/${rpool_name}/swap\tnone\tswap\tdiscard\t0 0\n' > ${strapdir}/etc/fstab"
	#printf "RESUME=none" > ${strapdir}/etc/initramfs-tools/conf.d/resume
	popd
	
	act "finalize"
	cat <<-EOF | sudo tee ${strapdir}/finalize >/dev/null
		#!/bin/sh

		## permissions
		for i in cdrom floppy sudo audio dip video plugdev netdev; do
		        gpasswd -a ${username} \$i
		done

		# Update the user home directory from /etc/skel. (or run scripts that populate /etc/skel before user creation.)
		#tar -cf - -C /etc/skel . | sudo -Hu "$username" tar --skip-old-files -xf -

		chsh -s "${default_shell}" ${username}
		chown -R 1000:1000 /home/${username}

		# the splash.png is copied in by the blend overlay
		if [[ -d /usr/lib/refractasnapshot/iso/isolinux ]]; then
		        cp /splash.png /usr/lib/refractasnapshot/iso/isolinux/
		fi

		rm -f /splash.png

		rm -f /etc/popularity-contest.conf

		# Disable contrib and non-free after installing firmware.
		#sed -i 's/contrib//g' /etc/apt/sources.list
		#sed -i 's/non-free//g' /etc/apt/sources.list
		#sed -i 's/non-free-firmware//g' /etc/apt/sources.list

		## package list - Why does this make an empty file?
		#dpkg -l | awk '/^ii/ { print $2 " " $3 }' > /home/${username}/package_list

		# Enable encryption (e.g. for live-usb with persistence)
		#sed -i 's/#CRYPTSETUP=/CRYPTSETUP=y/' /etc/cryptsetup-initramfs/conf-hook
		#CRYPTSETUP=y update-initramfs -u -k all

		apt-get update
		apt-get clean
		updatedb
	EOF
	chroot-script -d finalize || zerr
}
