#!/bin/bash

#set -e

# DEFAULT VALUES
#Live Build Astra directory
LBA="/usr/share/live-build-astra"
INCLUDES_CHROOT_DIR="${LBA}/includes.chroot"
INCLUDES_BINARY_DIR="${LBA}/includes.binary"
OUTPUT_FILE="system_live.iso"
BUILD_DIR="build"

USAGE=$(cat <<EOF
LiveCD converter
Usage: convert-to-live [OPTIONS]

OPTIONS
     -h|--help display this help and exit
     -o|--output <filename> set output file name
     -b|--build-directory <dirname> build in given directory
     -c|--clean-before clean build directory before build
     -C|--clean-after clean build directory after build
EOF
)

CURRENT_VERSION=$(uname -a | cut -d " " -f 3)
usage () {    
    echo "${USAGE}"
}

# SCRIPT STARTS HERE. No function declarations below.
PROGRAM="convert-to-live"
LONG_OPTIONS="help,output:,build-directory:,clean-before,clean-after"
LONG_OPTIONS="$(echo ${LONG_OPTIONS} | tr -d ' ')"
ARGUMENTS="$(getopt --longoptions ${LONG_OPTIONS} --name="${PROGRAM}" --options ho:b:cC --shell sh -- "${@}")"

if [ "${?}" != "0" ]
then
    Echo_error "TERMINATUS" >&2
    exit 1
fi

eval set -- "${ARGUMENTS}"

while true; do
    case "${1}" in
	-h|--help)
	    usage
	    exit 0
	    ;;
        -o|--output)
            OUTPUT_FILE="${2}"
	    shift 2
            ;;
        -b|--build-directory)
            BUILD_DIR="${2}"
	    shift 2
            ;;
        -c|--clean-before)
            CLEAN_BEFORE="true"
	    shift
            ;;
        -C|--clean-after)
            CLEAN_AFTER="false"
	    shift
            ;;
	--)
	    shift
	    break
	    ;;
	*)
	    Echo_error "internal error %s" "${0}"
	    exit 1
	    ;;
    esac
done

# Check if convert-to-live is ran from root.
if ! [ "$(id -u)" = "0" ]; then
    echo 'convert-to-live had to be ran from root or with sudo' >&2
    exit 1
fi

if [ "${CLEAN_BEFORE}" = "true" ]; then
    rm -rf ${BUILD_DIR}
fi

# Check if build directory exists and is empty. Create it if doesn't exist.
if [ -e ${BUILD_DIR} ]; then
    if ! [ -d ${BUILD_DIR} ]; then
	echo "${BUILD_DIR} exists and is not a directory. Aborting" >&2
	exit 2
    else
	[ "$(ls -A ${BUILD_DIR})" ] && echo "${BUILD_DIR} is not empty. Aborting" >&2 && exit 3
    fi
else
    mkdir -p ${BUILD_DIR}
fi

if [ ! -f /usr/share/initramfs-tools/scripts/init-bottom/fstab ]; then
    cp ${INCLUDES_CHROOT}/usr/share/initramfs-tools/scripts/init-bottom/fstab /usr/share/initramfs-tools/scripts/init-bottom/fstab
    update-initramfs -u -k ${CURRENT_VERSION}
fi

pushd ${BUILD_DIR} && \
cp -r ${INCLUDES_BINARY_DIR}/* ./ && \
cat > boot/grub/grub.cfg <<EOF
set default=0
set timeout=30
#search --no-floppy --set=root -l 'ISOIMAGE'

if loadfont /boot/grub/font.pf2 ; then
	set gfxmode=auto
	insmod efi_gop
	insmod efi_uga
	insmod gfxterm
	terminal_output gfxterm
fi

insmod png
if background_image /boot/grub/astra_boot.png; then
  set color_normal=light-gray/black
  set color_highlight=white/black
else
  set menu_color_normal=cyan/blue
  set menu_color_highlight=white/blue
fi

menuentry "Live System" {
	set gfxpayload=keep
	linux	/live/vmlinuz-${CURRENT_VERSION} boot=live clearfstab
	initrd	/live/initrd.img-${CURRENT_VERSION}
}
EOF
mkdir live && \
cp /boot/vmlinuz-${CURRENT_VERSION} live/
cp /boot/initrd.img-${CURRENT_VERSION} live/

mksquashfs / live/filesystem.squashfs -comp xz -wildcards -e boot -e proc/* -e sys/* -e dev/* -e $(pwd | sed 's/^\///')
popd

xorriso -as mkisofs -V "Orel Live" -iso-level 3 -isohybrid-mbr /usr/lib/syslinux/isohdpfx.bin -b boot/grub/grub_eltorito -no-emul-boot -boot-load-size 4 -boot-info-table -eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot -isohybrid-gpt-basdat -append_partition 2 0xef ${BUILD_DIR}/boot/grub/efi.img -o ${OUTPUT_FILE} ${BUILD_DIR}
