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

usage() {
  echo "Usage : $1 "
  echo "    -d <kernel_deb> extract this deb"
  echo "    -b extract kernel and headers for out of tree module build"
}

cwd=$(pwd)
kernel_deb=
build_prep=0
arch=arm64

while getopts "hd:b" opt; do
  case ${opt} in
    d)
      kernel_deb=$OPTARG
      ;;
    b)
      build_prep=1
      ;;
    \?)
      echo "Invalid Option: -$OPTARG" 1>&2
      usage "$0"
      exit 0
      ;;
    h )
      usage "$0"
      exit 0
      ;;
  esac
done

if [ -z ${kernel_deb} ]; then
    kernel_deb=`ls -t files/linux-image-* | grep -v dbg | head -n1`
fi

echo "Installing kernel ${kernel_deb}"

VERSION=${kernel_deb%_${arch}.deb}
VERSION=${VERSION##*/}
VERSION=${VERSION##linux-image-}
VERSION=${VERSION%_*}

SRC_DIR=`dirname ${kernel_deb}`

headers=${kernel_deb##*/}
headers=linux-headers-${headers##linux-image-}

if [ "${build_prep}" == 1 ]; then
    DIR=${cwd}/build/${VERSION}
    rm -r ${DIR}
else
    DIR=`mktemp -d -p build`
fi

echo "disecting debian kernel ${VERSION} in ${DIR}"

dpkg-deb -R ${kernel_deb} ${DIR}

if [ "${build_prep}" == 1 ]; then
    rm -r ${DIR}/DEBIAN
    dpkg-deb -R ${SRC_DIR}/${headers} ${DIR}
    rm -r ${DIR}/DEBIAN
    dpkg-deb -R ${SRC_DIR}/linux-libc-dev_${VERSION}*${arch}.deb ${DIR}
fi

mv ${DIR}/boot/vmlinuz-${VERSION} ${DIR}/boot/Image.gz
gunzip ${DIR}/boot/Image.gz 

cp ${DIR}/boot/Image files/
cp ${DIR}/usr/lib/linux-image-${VERSION}/freescale/*.dtb files/

if [ "${build_prep}" != 1 ]; then
    rm -r ${DIR}
fi

