#!/bin/bash
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2022] EMBL-European Bioinformatics Institute
# 
# 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.

# This script is called by 'git commit' just after doing the actual commit
# If the user has a config 'user.shared' as true, this script rewrites the
# just made commit to modify the committer and author as required

# if not a shared user
[ "$(git config user.shared)" != 'true' ] && exit 0

# get the saved identity
identity=$(git ensconfig --get)

if [ -n "$identity" ] ; then
  name=$(echo "$identity" | cut -d '<' -f 1 | sed 's/\s$//')
  email=$(echo "$identity" | cut -d '<' -f 2 | sed 's/>$//')
  stash=$(git stash | grep "^Saved" | wc -l);

  git filter-branch -f --env-filter "
    if [ \"\$GIT_AUTHOR_EMAIL\" == \"\$GIT_COMMITTER_EMAIL\" ] ; then
      export GIT_AUTHOR_EMAIL=\"$email\"
      export GIT_AUTHOR_NAME=\"$name\"
    fi
    export GIT_COMMITTER_EMAIL=\"$email\"
    export GIT_COMMITTER_NAME=\"$name\"
  " --  HEAD^..HEAD > /dev/null

  if [ "$stash" == "1" ] ; then
    git stash pop > /dev/null
  fi

  git log -n1 --format="%CgreenAuthor:%Creset    %aN <%aE>%n%CgreenCommitter:%Creset %cN <%cE>"

else
  echo "Some problem occoured while forcing the committer and author identity. Please check your git log before pushing your changes."
fi
