#!/bin/sh
#
# This is the live-build 3.x auto/config
#

set -e

: ${TOPDIR:=/usr/src/packages}

#
# TODO: move this to a separate function called from lb_config
#
get_prjconf_parameter()
{
    PARAM=$1
    BUILDCONFIG="/.build/build.dist"

    if [ ! -e $BUILDCONFIG ] && [ -d $TOPDIR/SOURCES ]
    then
	BUILDCONFIG=$( ls -1 $TOPDIR/SOURCES/_buildconfig* | head -n1 )
    fi

    if [ -e $BUILDCONFIG ]
    then
        grep -E "^%$PARAM " $BUILDCONFIG | sed "s/^%$PARAM //g" | tail -n1
    else
        echo "localbuild"
    fi
}

# default to the parent directory name
: ${RECIPEFILE:="$(basename $(pwd))"}
# for reproducible builds
if [ ! -z "$SOURCE_DATE_EPOCH" ]; then
    BUILD_TIME="$SOURCE_DATE_EPOCH"
else
    BUILD_TIME="$(date +%s)"
fi

BUILDSTAMP="$(date +"%Y%m%dT%H%M" -d @$BUILD_TIME)"

PROJECT_ID=$(get_prjconf_parameter _project)

# create environment file read by chroot hooks
cat <<EOF >> config/environment.chroot_hooks
BUILD_TIME="${BUILD_TIME}"
PROJECT_ID="${PROJECT_ID}"
RECIPEFILE="${RECIPEFILE}"
EOF

IMAGE_NAME="${RECIPEFILE%.livebuild}_${BUILDSTAMP}"

LINUX_FLAVOURS=$(grep -s -h linux-image config/package-lists/*.chroot | sed "s/linux-image-//g")

if [ -z "$LINUX_FLAVOURS" ]; then
    LINUX_FLAVOURS="amd64"
fi

lb config noauto \
    --apt apt \
    --apt-recommends false \
    --apt-indices false \
    --apt-source-archives false \
    --apt-options "--yes -o Acquire::Check-Valid-Until=false" \
    --bootappend-live "boot=live components splash username=root console=tty0 console=ttyS0" \
    --bootappend-live-failsafe "boot=live components username=root debug live-boot.debug memtest noapic noapm nodma nomce nolapic nomodeset nosmp nosplash vga=normal console=tty0 console=ttyS0" \
    --bootloaders syslinux,grub-efi \
    --cache-indices false \
    --checksums "md5 sha256" \
    --chroot-filesystem squashfs \
    --debconf-frontend noninteractive \
    --distribution stable \
    --parent-distribution stable \
    --firmware-binary false \
    --firmware-chroot false \
    --ignore-system-defaults \
    --image-name "${IMAGE_NAME}" \
    --initramfs live-boot \
    --linux-flavours "${LINUX_FLAVOURS}" \
    --mode debian \
    --source false \
    --security true \
    --updates true \
    --backports false \
    --verbose \
    --onie true \
    --onie-kernel-cmdline "systemd.show_status=1 net.ifnames=1" \
    "${@}"
