#!/bin/bash

device="$1"
stowaway=""
boot=""
root_vg=""
root_lv=""
cmdline=$(</proc/cmdline)

base=0x40080000
second_offset=0x00e80000
kernel_offset=0x00000000
ramdisk_offset=0x04f80000
tags_offset=0x03f80000
pagesize=2048
kernel="/usr/share/kernel/Image.gz-dtb"
ramdisk="/usr/share/kernel/initrd.img-gemini.cpio.gz"
output="/usr/share/kernel/linux-boot.img"
cmdline_extra=""

if [[ -z "$device" ]]
then
  if [[ "$cmdline" =~ ^(.*)androidboot.hardware\=mt6797(.*)$ ]];
  then
    device="geminipda"
  fi

  if [[ "$cmdline" =~ ^(.*)androidboot.hardware\=mt6771(.*)$ ]];
  then
    device="cosmocom"
  fi
fi

case $device in
  geminipda)
    ramdisk_offset=0x04f80000
    tags_offset=0x03f80000
    ;;

  cosmocom)
    ramdisk_offset=0x14f80000
    tags_offset=0x13f80000
    ;;

  *)
    echo "Unknown device. Please provide either geminipda or cosmocom as an argument."
    echo "Skipping linux-boot.img creation."
    exit 0
    ;;
esac

echo "Device is $device"

if [[ "$cmdline" =~ ^(.*)bootpartition\=([_a-zA-Z0-9\-]*)(.*)$ ]];
then
  boot="${BASH_REMATCH[2]}"
fi

if [[ "$cmdline" =~ ^(.*)stowaways_os\=([_a-zA-Z0-9\-]*)(.*)$ ]];
then
  stowaway="${BASH_REMATCH[2]}"
fi

if [[ "$cmdline" =~ ^(.*)root_vg\=([_a-zA-Z0-9\-]*)(.*)$ ]];
then
  root_vg="${BASH_REMATCH[2]}"
fi

if [[ "$cmdline" =~ ^(.*)root_lv\=([_a-zA-Z0-9\-]*)(.*)$ ]];
then
  root_lv="${BASH_REMATCH[2]}"
fi

if [ -z "$stowaway" ] && [ -z "$root_lv" ]
then
  output="/usr/share/kernel/linux-boot.img"
fi

if [ -n "$stowaway" ]
then
  output="/usr/share/kernel/linux-boot-stowaways-${stowaway}.img"
  cmdline_extra="stowaways_os=${stowaway}"
fi

if [ -n "$root_lv" ] && [ -z "$root_vg" ]
then
  output="/usr/share/kernel/linux-boot-lvm-${root_lv}.img"
  cmdline_extra="root_lv=${root_lv}"
fi

if [ -n "$root_lv" ] && [ -n "$root_vg" ]
then
  output="/usr/share/kernel/linux-boot-lvm-${root_vg}-${root_lv}.img"
  cmdline_extra="root_vg=${root_vg} root_lv=${root_lv}"
fi

mkbootimg --kernel ${kernel} --ramdisk ${ramdisk} --base ${base} --second_offset ${second_offset} --cmdline "bootopt=64S3,32N2,64N2 log_buf_len=4M ${cmdline_extra}" --kernel_offset ${kernel_offset} --ramdisk_offset ${ramdisk_offset} --tags_offset ${tags_offset} --pagesize ${pagesize} -o ${output}

echo ""
echo "Kernel images installed to /usr/share/kernel/"

if [ -z "$boot" ]
then
  echo "Note: Old boot loader detected, you should flash the kernel manually. Please select kernel and boot partition as appropriate to your setup, taking particular reference to the boot time keys you hold to start Gemian"
  boot="boot2"
  echo "sudo dd if=${output} of=/dev/disk/by-partlabel/${boot}"
fi

echo "Flashing ${output} to /dev/disk/by-partlabel/${boot}"

dd if=${output} of=/dev/disk/by-partlabel/${boot}

echo "After writing the kernel image a reboot is necessary to use the new kernel."
echo ""
