#!/bin/bash

# Copyright (c) 2013 The CoreOS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

set -e

USAGE="Usage: $0 [-k 4.6.0] [-r /build/amd64-usr] [-o bootengine.cpio]
Options:
    -k VERSION  Kernel version of modules to include
    -r SYSROOT  Build the initrd using the given directory
    -o OUT.cpio Alternate path to write the initrd

This tool uses dracut to update /usr/share/bootengine/bootengine.cpio
"

DRACUT_ARGS=(
    --force
    --no-hostonly
    --no-compress
    --omit "fido2 lvm multipath network pkcs11 tpm2-tss zfs"
    --add "i18n iscsi"
    --add-drivers "loop brd drbd nbd rbd mmc_block xen-blkfront zram libarc4 lru_cache zsmalloc"
    --kernel-cmdline "SYSTEMD_SULOGIN_FORCE=1"
    )

USE_SYSROOT=
CPIO_PATH=
KERNEL=
while getopts "hk:o:r:" OPTION
do
    case $OPTION in
        k) KERNEL="$OPTARG";;
        o) CPIO_PATH="$OPTARG";;
        r) USE_SYSROOT="$OPTARG";;
        h) echo "$USAGE"; exit;;
        *) exit 1;;
    esac
done

if [[ -n "$USE_SYSROOT" && ! -d "$USE_SYSROOT" ]]; then
    echo "$0: sysroot directory $USE_SYSROOT does not exist!" >&2
    exit 1
fi

if [[ $(id -u) -ne 0 ]]; then
    echo "$0: this script must be run as root!" >&2
    exit 1
fi

if [[ -n $USE_SYSROOT ]]; then
    DRACUT_ARGS+=( --sysroot "${USE_SYSROOT}" )
fi

: "${CPIO_PATH:=${USE_SYSROOT}/usr/share/bootengine/bootengine.cpio}"

if [[ -n "$KERNEL" ]]; then
    DRACUT_ARGS+=(
        --kver "${KERNEL}"
        --kmoddir "${USE_SYSROOT}/lib/modules/${KERNEL}"
    )
else
    DRACUT_ARGS+=( "--no-kernel" )
fi

# Copying / installing files to initrd while preserving xattrs breaks dracut in certain scenarios,
#  e.g. when run in a container.
DRACUT_NO_XATTR=1
export DRACUT_NO_XATTR

mkdir -p "${CPIO_PATH%/*}"
LC_ALL=C DRACUT_INSTALL=/usr/lib/dracut/dracut-install dracut "${DRACUT_ARGS[@]}" "$CPIO_PATH"
chmod 644 "${CPIO_PATH}"
