#!/bin/sh

#
# Copyright (C) 2019 Signal Messenger, LLC.
# All rights reserved.
#
# SPDX-License-Identifier: GPL-3.0-only
#

set -e

BIN_DIR="$(realpath -e $(dirname $0))"
. "${BIN_DIR}/env.sh"

[ -d "$PATCH_DIR" ] || {
    echo "ERROR: patch directory does not exist: $PATCH_DIR"
    exit 1
}

SRC_ROOT="$(realpath -e $WEBRTC_DIR/src)"
[ -d "$SRC_ROOT" ] || {
    echo "ERROR: target source directory does not exist: $SRC_ROOT"
    exit 1
}

PATCH_TAG=pre-patch
PATCH_BRANCH=patched-src

for series in $(find "$PATCH_DIR" -type f -name series) ; do

    echo "Applying patches from: $series"
    DIR=$(dirname "$series")
    DIR="${DIR#${PATCH_DIR}}"
    REPO_DIR="${SRC_ROOT}$DIR"
    cd "$REPO_DIR"
    if [ "$(git tag -l $PATCH_TAG)X" != "X" -o  "$(git branch --list $PATCH_BRANCH)X" != "X" ] ; then
        echo "Repo already patched: $REPO_DIR, skipping..."
        continue
    fi
    git tag $PATCH_TAG
    git checkout -b $PATCH_BRANCH
    git commit -m "Unmodified $(basename $REPO_DIR) src" --allow-empty > /dev/null
    stg init
    stg import -s "$series"
    echo -e "%(description)s\n" > .git/patchexport.tmpl

done
