#!/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 "Reversing patches from: $series"
    DIR=$(dirname "$series")
    DIR="${DIR#${PATCH_DIR}}"
    REPO_DIR="${SRC_ROOT}$DIR"
    cd "$REPO_DIR"
    git checkout master
    stg branch --delete --force $PATCH_BRANCH
    git checkout $PATCH_TAG
    git tag -d $PATCH_TAG
    # git clean -dfx

done

# the 'git clean -dfx' is kind of drastic, undoing a bunch of stuff
# that 'gclient sync' has done.
