#!/bin/bash
#
# Copyright (C) 2018 Purism SPC
#
# SPDX-License-Identifier: GPL-3.0+
#

set -e

usage() {
  echo "Usage : $0 -t <rootfs tarball> -o <initramfs>"
  echo "    -i <path> install local kernel from path"
}

build_initrd=0
customize=1
tar_file=
initramfs=

while getopts "t:o:i:" opt; do
  case ${opt} in
    t)
      tar_file=$OPTARG
      ;;
    o)
      initramfs=$OPTARG
      ;;
    i)
      kernel_path=$OPTARG
      ;;
    \?)
      echo "Invalid Option: -$OPTARG" 1>&2
      usage "$0"
      exit 0
      ;;
    h )
      usage "$0"
      exit 0
      ;;
  esac
done

if [ -z "${tar_file}" ] || [  -z "${initramfs}" ]; then
    usage
    exit 1
fi

[ ! -e build ] && mkdir -p build
    
DIR=`mktemp -d`
BASE=`basename ${initramfs}`
cwd=`pwd`

echo "Creating initramfs ${initramfs} from ${tar_file} in ${DIR}"
fakeroot tar -xf ${tar_file} -C ${DIR}
if [ ! -z "${kernel_path}" ]; then
    cp ${kernel_path}/arch/arm64/boot/Image files/
    cp ${kernel_path}/arch/arm64/boot/dts/freescale/librem5-evk.dtb files/
    fakeroot rm -rf ${DIR}/lib/modules/*
    cd ${kernel_path} && make modules_install INSTALL_MOD_PATH=${DIR}
    find ${DIR}/lib/modules -name "*.ko" -exec aarch64-linux-gnu-strip --strip-debug \{\} \;
    cd ${cwd}
fi 

if [ "${customize}" == 1 ]; then
    fakeroot scripts/root.sh ${DIR}
fi

cd ${DIR}
if [ "${build_initrd}" == 1 ]; then
    find . -print0 | cpio --null -o --format=newc | gzip -9 > ${cwd}/build/${BASE}.image
else
    fakeroot genext2fs -d . -N 24000 -b 350000 ${cwd}/build/${BASE}.image
fi

#gzip ${cwd}/build/${BASE}.image
mkimage -n 'Test Ramdisk' -A arm64 -O linux -T ramdisk -C gzip -d ${cwd}/build/${BASE}.image ${cwd}/${initramfs}
cd ${cwd}

rm -fr ${DIR}
