#!/bin/bash

# Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

if [ -z "$1" ]; then
    echo "Usage1: patch_from_github PATCHFILE (generated by 'diff diff --no-prefix')"
    echo "Usage2: patch_from_github GIT_DIR COMMIT"
    exit 1
fi
PATCHFILE=$1
if [ -d "$1/.git" ]; then
    if [ -z "$2" ]; then
        echo "Second argument must be a git commit"
        exit 1
    fi
    CURRENT_DIR=`pwd`
    GIT_DIR=$1
    COMMIT=$2
    PATCHFILE=$CURRENT_DIR/$COMMIT.patch
    echo "*** Generating diff of $GIT_DIR@$COMMIT"
    cd $GIT_DIR && git diff --no-prefix $COMMIT^! > $PATCHFILE
    cd $CURRENT_DIR
fi

MODIFIED_PATCHFILE=$(basename $(basename $PATCHFILE .patch) .diff).from_github.patch

cat $PATCHFILE | sed -e 's/src\/baidu\/rpc\//src\/brpc\//g' \
            -e 's/\<baidu\/rpc\//brpc\//g' \
            -e 's/\<baidu::rpc::/brpc::/g' \
            -e 's/\<base::/butil::/g' \
            -e 's/\<base\//butil\//g' \
            -e 's/\<namespace \+raft/namespace braft/g' \
            -e 's/\<protocol\/raft\/\(\S*\)\.proto/src\/braft\/\1.proto/g' \
            -e 's/src\/raft\/test\/\(\S*\)\.cpp/test\/\1.cpp/g' \
            -e 's/\<raft::/braft::/g' \
            -e 's/\<raft\//braft\//g' \
            -e 's/tools\/raft_cli.cpp/tools\/braft_cli.cpp/g' \
            > $MODIFIED_PATCHFILE
EXTRA_ARGS=
if [ -z "$DO_RUN" ]; then
    EXTRA_ARGS="--dry-run $EXTRA_ARGS"
    echo "*** This is a dry-run. To really apply, run: DO_RUN=1 tools/patch_from_github $1"
fi

patch -p0 -u -l $EXTRA_ARGS < $MODIFIED_PATCHFILE
if [ ! -z "$DO_RUN" ]; then
    REJ_FILES=`find . -name "*.rej"`
    if [ ! -z "$REJ_FILES" ]; then
        echo "==== The patching is not done yet! Apply following rej files manually ===="
        echo $REJ_FILES
    fi
fi
