#!/usr/bin/env bash

#set -eET -o pipefail
#trap 'echo $(basename ${BASH_SOURCE[0]}):${LINENO}: "${BASH_COMMAND}"' DEBUG
export setCompatFlags top LMK setCompatFlags
trap 'rm -rf ${TOP}/${INITRAMFS}{,.img};exit ${?}' INT TERM
cd "$(dirname $(readlink -f ${0}))"||false
. ../.config||false

#add more ELFs, if need ;)
list=(bash blkid tar e2fsck fsck.fat fsck.f2fs mdadm mount.ntfs-3g)

# copy file to initramfs tree, including
# all library dependencies (as shown by ldd)
# ${1} = file to copy (full path)
copy_including_deps()
{
   # if source doesn't exist or target exists, do nothing
   if [[ ! -e "${1}" || -e "${INITRAMFS}"/"${1}" || -e ${INITRAMFS}"/${2}" ]]; then
      return 1
   fi

   [ ${2} ]&&cp -r -T $([ ${V} ]&&echo ${V}) "${1}" "${INITRAMFS}/bin"||cp -r --parents $([ ${V} ]&&echo ${V}) "${1}" "${INITRAMFS}"
   if [ -L "${1}" ]; then
      DIR="$(dirname "${1}")"
      LNK="$(readlink "${1}")"
      copy_including_deps "$(cd "$DIR"; realpath -s "$LNK")"
   fi

   ldd "${1}" 2>/dev/null | sed -r "s/.*=>|[(].*//g" | sed -r "s/^\\s+|\\s+\$//" \
     | while read LIB; do
        copy_including_deps "$LIB"
     done

   for MOD in $(find "${1}" -type f -name "*.ko"); do
      for DEP in $(cat /$LMK/modules.dep | fgrep /$(basename $MOD):); do
         copy_including_deps "/$LMK/$DEP"
      done
   done

   shift
   if [ "${1}" != "" ]; then
       copy_including_deps "${@}"
   fi
}
incDynElf()
{
   local f
   f="$(type -P ${1})"
   copy_including_deps ${f} /bin/$(basename ${f})
   return ${?}
}

mkdir -p ${INITRAMFS}/{bin,dev,etc,lib{32,64,x32,},mnt,proc,root,run,sys,tmp,usr{,/local}/{sbin,bin,lib{32,64,x32,}},var/log}

# If bb is not found use all static prebuilt
incDynElf busybox || { cp -f static/busybox ${INITRAMFS}/bin;static=true; }
for i in $(${INITRAMFS}/bin/busybox --list|egrep -v "tar|init|blkid"); do ln -sf $([ ${V} ]&&echo ${V}) busybox ${INITRAMFS}/bin/$i; done

mknod ${INITRAMFS}/dev/console c 5 1
mknod ${INITRAMFS}/dev/null c 1 3
mknod ${INITRAMFS}/dev/ram0 b 1 0
mknod ${INITRAMFS}/dev/tty1 c 4 1
mknod ${INITRAMFS}/dev/tty2 c 4 2
mknod ${INITRAMFS}/dev/tty3 c 4 3
mknod ${INITRAMFS}/dev/tty4 c 4 4


for i in /$LMK/kernel/fs $(find /$LMK/kernel/ | grep crc32) /$LMK/kernel/drivers/staging/zsmalloc /$LMK/kernel/drivers/block/zram /$LMK/kernel/drivers/block/loop.* /$LMK/kernel/drivers/usb/storage/usb-storage.* /$LMK/kernel/drivers/usb/host /$LMK/kernel/drivers/usb/common /$LMK/kernel/drivers/usb/core /$LMK/kernel/drivers/hid/usbhid /$LMK/kernel/drivers/hid/hid.* /$LMK/kernel/drivers/hid/uhid.* /$LMK/kernel/drivers/hid/hid-generic.* /$LMK/kernel/drivers/cdrom /$LMK/kernel/drivers/scsi/sr_mod.* /$LMK/kernel/drivers/scsi/sd_mod.* /$LMK/kernel/drivers/scsi/scsi_mod.* /$LMK/kernel/drivers/scsi/sg.* /$LMK/kernel/drivers/ata /$LMK/kernel/drivers/nvme /$LMK/kernel/drivers/mmc /$LMK/updates /$LMK/modules.*; do copy_including_deps ${i};done

cp -f $([ ${V} ]&&echo ${V}) static/mount.dynfilefs static/fsck ${top}/ext/checkbox/checkbox.sh ${INITRAMFS}/bin
if [[ ${static} ]]; then
   for i in "${list[@]}"; do
      cp -f $([ ${V} ]&&echo ${V}) static/${i} ${INITRAMFS}/bin
   done
else
   for i in "${list[@]}"; do
      incDynElf ${i}
   done
fi
# trim modules.order file. Perhaps we could remove it entirely
MODULEORDER="$(cd "${INITRAMFS}/$LMK/"; find . -name "*.ko" | sed -r "s:^./::g" | tr "\n" "|" | sed -r "s:[.]:.:g")"
cat ${INITRAMFS}/$LMK/modules.order | sed -r "s/.ko.gz\$/.ko/" | grep -E "$MODULEORDER"/foo/bar > ${INITRAMFS}/$LMK/_
mv -f $([ ${V} ]&&echo ${V}) ${INITRAMFS}/$LMK/_ ${INITRAMFS}/$LMK/modules.order

depmod -b ${INITRAMFS} $(ls ${INITRAMFS}/lib/modules | sort)

echo "root::0:0::/root:/bin/bash" >${INITRAMFS}/etc/passwd
:>${INITRAMFS}/etc/{m,fs}tab

cp -f $([ ${V} ]&&echo ${V}) functions ${INITRAMFS}/lib
cp -f $([ ${V} ]&&echo ${V}) init shutdown  ${INITRAMFS}
ln -sf $([ ${V} ]&&echo ${V}) ../init ${INITRAMFS}/bin/init
cp -f $([ ${V} ]&&echo ${V}) ../.config ${INITRAMFS}/lib
chmod a+x -R $([ ${V} ]&&echo ${V}) ${INITRAMFS}

cd ${INITRAMFS}
find lib usr{,/local}/lib -name "*.so" -exec sh -c 'ln -s ${1} lib/$(basename ${1})' _ {} \;
# for d in {s,}bin usr{,/local}/{s,}bin; do
#    for f in ${d}/*; do
#       ln -s ${f} bin
#    done
# done

find . | cpio -R root:root -o -H newc 2>/dev/null | gzip -cf9 >${INITRAMFS}.img
cd ..
rm -rf ${INITRAMFS}
[[ ${static} ]]&&exit 2||exit 0
