#!/usr/bin/env bash

# whatsmeow-mkpatch
#
# Copyright (c) 2026 Kristofer Berggren
# All rights reserved.
#
# whatsmeow-mkpatch is distributed under the MIT license.

SYNCNAME="whatsmeow"
TARGET="lib/wmchat/go/ext/whatsmeow"
PATCHFILE="lib/wmchat/go/ext/nchat-whatsmeow.patch"

if [[ "${1}" == "-h" ]]; then
  echo "usage: ./utils/whatsmeow-mkpatch [commit]"
  exit 0
fi

exiterr()
{
  >&2 echo "${1}"
  exit 1
}

REPOROOT="$(git rev-parse --show-toplevel)"
if [[ "${REPOROOT}" == "" ]]; then
  exit 1
fi

# Check external whatsmeow repo
REPOPARENT=$(dirname "${REPOROOT}")
SYNCDIR="${REPOPARENT}/${SYNCNAME}"
[[ -d "${SYNCDIR}" ]] || exiterr "external whatsmeow repo not found at ${SYNCDIR} - run whatsmeow-update first"

# Check for uncommitted changes in external whatsmeow dir
cd "${SYNCDIR}"
git diff --quiet HEAD -- "${SYNCDIR}" || exiterr "external whatsmeow dir has uncommitted changes"
cd "${REPOROOT}"

# Checkout specified commit in external whatsmeow repo
if [[ "${1}" != "" ]]; then
  echo "Checkout"
  COMMIT="${1}"
  pushd "${SYNCDIR}" > /dev/null || exiterr "pushd failed"
  git checkout ${COMMIT} || exiterr "git checkout ${COMMIT} failed"
  git clean -ffdx || exiterr "git clean failed"
  popd > /dev/null || exiterr "popd failed"
fi

# Sync nchat customizations to whatsmeow repo
echo "Sync"
REPOTARGET="${REPOROOT}/${TARGET}"
pushd "${SYNCDIR}" > /dev/null || exiterr "pushd failed"
${REPOROOT}/utils/cvc sync "${REPOTARGET}" || exiterr "cvc sync failed"

# Generate patch
echo "Diff"
${REPOROOT}/utils/cvc diff > "${REPOROOT}/${PATCHFILE}"
if [[ ! -s "${REPOROOT}/${PATCHFILE}" ]]; then
  rm -f "${REPOROOT}/${PATCHFILE}"
  git checkout HEAD -- . || true
  git clean -ffdx || true
  popd > /dev/null || exiterr "popd failed"
  exiterr "no differences found - patch file not created"
fi

# Restore whatsmeow repo
echo "Restore"
git checkout HEAD -- . || exiterr "restore failed"
git clean -ffdx || exiterr "clean failed"
popd > /dev/null || exiterr "popd failed"

echo "Done - patch saved to ${PATCHFILE}"
exit 0
