#!/bin/bash -e
readonly ROOT_DIR="$(dirname $(readlink -f ${BASH_SOURCE[0]}))"

readonly SPEC_FILE="$(find . -name '*.spec' | head -n 1)"
readonly REPO_NAME="$(basename ${SPEC_FILE} | sed 's/.spec//')"
readonly REPO_VERSION="$(grep Version ${SPEC_FILE} | head -n 1 | awk -F ' ' '{print $NF}')"
readonly REPO_REMOTE="origin"

readonly PKG_NAME="${REPO_NAME}-${REPO_VERSION}"
readonly PKG_DIR="${ROOT_DIR}/${PKG_NAME}"
readonly PKG_BRANCH="$(git branch --show-current | sed 's/-LTS.*//')"

echo "Preparing..."
# clean old files
rm -f ${ROOT_DIR}/*.patch
rm -rf ${PKG_DIR}

# extract package
tar -xf ${PKG_NAME}.tar.gz

# fetch baseline
pushd ${PKG_DIR} > /dev/null
readonly PKG_BASELINE=$(git rev-parse --short HEAD)
popd > /dev/null

echo "------------------------------"
echo "Name:     ${PKG_NAME}"
echo "Branch:   ${PKG_BRANCH}"
echo "Baseline: ${PKG_BASELINE}"
echo "------------------------------"

echo "Syncing with remote..."
pushd ${PKG_DIR} > /dev/null
git fetch ${REPO_REMOTE}
popd > /dev/null

echo "Generating patches..."
# format patches
pushd ${PKG_DIR} > /dev/null
git checkout -q ${REPO_REMOTE}/${PKG_BRANCH}
git format-patch -qN -o ${ROOT_DIR} ${PKG_BASELINE}
popd > /dev/null

# print patch list
patch_list="$(find ${ROOT_DIR} -maxdepth 1 -name "*.patch" | sort)"
for patch_file in ${patch_list}; do
    patch_name="$(basename ${patch_file})"
    patch_id="$(echo ${patch_name} | awk -F '-' '{print $1}')"
    echo "Patch${patch_id}: ${patch_name}"
done

echo "Cleaning up..."
rm -rf ${PKG_DIR}

echo "Done"
