#!/bin/sh
set -eu

if [ "$#" -ne 3 ]; then
    printf '%s\n' "usage: $0 CHEESED_BINARY STATIC_TCSH OUTPUT" >&2
    exit 2
fi

cheesed_binary=$1
tcsh_binary=$2
output=$3

for binary in "$cheesed_binary" "$tcsh_binary"; do
    if [ ! -x "$binary" ]; then
        printf '%s\n' "not an executable file: $binary" >&2
        exit 1
    fi
    if ! file "$binary" | grep -Eq 'statically linked|static-pie linked'; then
        printf '%s\n' "initramfs input must be statically linked: $binary" >&2
        exit 1
    fi
done

staging=$(mktemp -d "${TMPDIR:-/tmp}/cheesed-initramfs.XXXXXX")
trap 'rm -rf "$staging"' EXIT HUP INT TERM

mkdir -p "$staging/bin" "$staging/dev" "$staging/proc" "$staging/root" "$staging/sbin" "$staging/sys"
cp "$cheesed_binary" "$staging/sbin/cheesed"
cp "$tcsh_binary" "$staging/bin/tcsh"

(
    cd "$staging"
    find . -print | cpio -o -H newc 2>/dev/null | gzip -9
) >"$output"

printf '%s\n' "$output"
