#!/bin/sh
BOOTPART=/dev/mmcblk0p1

umount /boot || true
if mount | grep '/dev/mmcblk.p6' | grep -q '/boot' ; then
  BOOTPART=`mount | grep '/dev/mmcblk.p6' | grep '/boot' | cut -d ' ' -f1`
  mkdir -p /media/boot
  if df -h /boot/efi/ | grep -q $BOOTPART ; then
    mount -o bind /boot/efi /media/boot
  else
    mount $BOOTPART /media/boot
  fi
elif [ ! -e /dev/mmcblk0p1 ]; then
  BOOTPART=/dev/mmcblk1p1
  mount /dev/mmcblk1p1 /media/boot/ || true
else
  mount /dev/mmcblk0p1 /media/boot/ || true
fi

dpkg -i linux-image-?.*.*_?.*.*-*-rockpro64*_arm64.deb 

kver=none
for f in `ls linux-image-*_*_*.deb`; do
    kver=`echo $f | cut -d "_" -f 1 | cut -d - -f 3-`
done

kdtb=none.dtb
for f in `ls /boot/*.dtb-${kver} 2> /dev/null`; do
   b=`basename $f`
   b=/media/boot/${b/-$kver/}
   if [ ! -e $b ] ; then
       cp -p $f $b
       kdtb=$f
   fi
done

for f in logo*.bmp ; do
  if [ -e $f -a ! -e /media/boot/$f ]; then
    if [ -e /media/boot ]; then
      cp $f /media/boot/
    fi
  fi
done

if [ -e /usr/lib/linux-image-${kver} ]; then
  for f in `ls /usr/lib/linux-image-${kver}/rk3399-rockpro64.dtb /usr/lib/linux-image-${kver}/rockchip/rk3399-rockpro64.dtb 2> /dev/null`; do
     if [ -e $f  ]; then
         b=`basename $f`
         b=/media/boot/${b}
         cp -p $f $b
         kdtb=$f
     fi
  done
  ./install-dtb.sh $kver
fi

kimg=none
for f in `ls /boot/vmlinu?-${kver} 2> /dev/null`; do
    kimg=$f
done

if [ -e $kimg ]; then
  b=`basename $kimg`
  echo Using $b

  ./install-image.sh $kver $kimg
fi

update-initramfs -c -k $kver || update-initramfs -u -k $kver
if [ -e $kdtb ]; then
  ./install-uinitrd.sh $kver
fi

if [ -e 10-efuse.rules ]; then
  if [ ! -e /etc/udev/rules.d/10-efuse.rules ]; then
    cp -p 10-efuse.rules /etc/udev/rules.d/
  fi
fi

echo OK
