#!/bin/bash
set -e

cd $(dirname $0)/..

source ./scripts/version

BASEDOCKERFILE=./scripts/installer/BaseDockerfile.${ARCH}
DOCKERFILE=./scripts/installer/Dockerfile.${ARCH}
ARTIFACTS=./dist/artifacts

if \
      [[ "${ARCH}" != "amd64" ]] || \
      [ ! -f ${ARTIFACTS}/vmlinuz-${KERNEL_VERSION} ] || \
      [ ! -f ${ARTIFACTS}/${INITRD} ]; \
      then
    echo "Skipping package-installer due to ARM/ARM64 build: ${ARTIFACTS}/vmlinuz-${KERNEL_VERSION}  or ${ARTIFACTS}/${INITRD} not found"
    exit 0
fi

# build kexec
pushd .
cd scripts/installer/kexec
dapper
popd


# TODO maybe extract the creation of the syslinux cfg files
DIST=$(pwd)/dist
echo "mkdir -p ${DIST}/boot/isolinux/"
mkdir -p ${DIST}/boot/isolinux/
cat scripts/isolinux.cfg | envsubst >         ${DIST}/boot/isolinux/isolinux.cfg
cat scripts/isolinux_label.cfg | LABEL=${VERSION} envsubst >   ${DIST}/boot/linux-current.cfg
#cat scripts/isolinux_label.cfg | LABEL=debug APPEND="rancher.debug=true" envsubst >   ${DIST}/boot/linux-previous.cfg
cat scripts/global.cfg | LABEL=${VERSION} envsubst >   ${DIST}/boot/global.cfg
cp scripts/rancher.png ${DIST}/boot/


mkdir -p ./scripts/installer/build/boot
cp ./bin/ros ./scripts/installer/build
trap "rm -rf ./scripts/installer/build" EXIT

# installer base image - can be included in iso
# TODO: fix the fullinstaller Dockerfile to use the ${VERSION}${SUFFIX}
docker build \
    -t ${OS_REPO}/os-installer \
    --build-arg VERSION=${VERSION} \
    --build-arg KERNEL_VERSION=${KERNEL_VERSION} \
    -f $BASEDOCKERFILE \
    ./scripts/installer
docker save -o ${ARTIFACTS}/installer.tar ${OS_REPO}/os-installer
cp $DOCKERFILE ${ARTIFACTS}/

cp ${ARTIFACTS}/${INITRD} ./scripts/installer/build/boot
cp ${ARTIFACTS}/vmlinuz-${KERNEL_VERSION} ./scripts/installer/build/boot
cp -r ${DIST}/boot/* ./scripts/installer/build/boot
cp $DOCKERFILE ./scripts/installer/build/Dockerfile
# Full installer image with initrd - used for pulling from network
docker build \
    -t ${OS_REPO}/os \
    ./scripts/installer/build
docker tag ${OS_REPO}/os ${OS_REPO}/os:${VERSION}${SUFFIX}

docker save -o ${ARTIFACTS}/fullinstaller.tar ${OS_REPO}/os:${VERSION}${SUFFIX}
echo ${OS_REPO}/os:${VERSION}${SUFFIX} >> dist/images
echo Built ${OS_REPO}/os:${VERSION}${SUFFIX}
