#!/usr/bin/env bash
set -x

sudo apt-get update
sudo apt-get install git-buildpackage devscripts python3-debian

# mk-build-deps

# /etc/devscripts.conf
# DEBCOMMIT_SIGN_COMMITS=yes
# DEBSIGN_PROGRAM=gpg
# DEBSIGN_MAINT="Bhaskar Chowdhury"
# DEBSIGN_KEYID=9F017E9D66B07216543CEBB0B23A9DB7114B2915
# DGET_VERIFY=yes

kernel_version=6.6.28

ARCH=$(dpkg --print-architecture)
PACKAGE=linux-signed-${ARCH}-git
BUILD_HOME="/var/tmp/debian-kernel_gbp"
PATCH_DIR=${BUILD_HOME}/patches
BUILD_DEST="${BUILD_HOME}/${PACKAGE}"
DEBIAN_BRANCH=debian/6.7.12-1
UPSTREAM_BRANCH=upstream/latest
# REMOTE_REPO=https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
REMOTE_REPO=https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/
REPO=/space/code_repositories/decode-os/os-build-system/arm-sdk/tmp/kernels/rockpro64/rockpro64-linux_v6.6.10/

# fetch libreELEC patches
mkdir -p ${PATCH_DIR}
# wget \
#	--show-progress \
#	--directory-prefix=${PATCHES_DIR} \
#  https://github.com/LibreELEC/LibreELEC.tv/raw/master/projects/Rockchip/patches/linux/default/*.patch
cp -a /space/code_repositories/test-kernel-patches/projects/LibreELEC.tv/projects/Rockchip/patches/linux/default/*.patch \
  ${PATCH_DIR}

# Pull the upstream sources
mkdir -p ${BUILD_DEST}
gbp clone \
  --pristine-tar \
  --debian-branch=${DEBIAN_BRANCH} \
  --upstream-branch=${UPSTREAM_BRANCH} \
  --add-upstream-vcs \
  --verbose \
  https://salsa.debian.org/kernel-team/linux.git ${BUILD_DEST}

pushd ${BUILD_DEST}
git checkout ${DEBIAN_BRANCH}

# This will produce ../orig/linux_<version>.orig.tar.xz need by the following make target
./debian/bin/genorig.py ${REMOTE_REPO}

# This will apply the main quilt series to the upstream source
cd make -f debian/rules orig

# Patch the sources
gbp pq --time-machine=10 --force import
gbp pq import ${PATCH_DIR}/*.patch
gbp pq apply

# Export the Patches and Commit the Changes:
gbp pq export --commit -v debian/patches/features/arm64

# Post patch / rebase commit.
git add debian/patches
git commit -m "Applied Rockchip patches."

popd
