#!/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 extra command provides a way to set/get/unset current user's identity
# if the actual git user is a shared user (eg. www-ens or ensembl)

# Find out the current shell pid against which the user info is saved
shell_id=$(ps | sed -r 's/\s+/ /g' | sed 's/^\s//' | cut -d ' ' -f 1,4 | grep $(echo $SHELL | sed -r 's/^.+\///' ) | sort -n | tr ' ' '_' | head -1)

# Centralised config file
config_file="$HOME/.gitensconfig"

touch "$config_file"

usage="usage: git ensconfig [options]"$'\n'"
    --set <identity>  set the user name and email eg. 'git ensconfig --set \"A U Thor <author@example.com>\"'
    --unset           remove the previously set name and email
    --get             get the user name and email"$'\n'

if (( $# >= 1 )) ; then

  case $1 in
    "--set" )
      if [ "$#" == 2 ] ; then
        identity=$(echo $2 | sed -r -n '/^[^<]+<[^>]+>$/p')
        if [ -z "$identity" ] ; then
          echo "Please provide valid identity."$'\n'$'\n'"$usage"
          exit 1
        fi
        sed -i "/^$shell_id/d" "$config_file"
        echo "$shell_id $identity" >> "$config_file"
        exit 0
      fi
    ;;
    "--unset" )
      if [ "$#" == 1 ] ; then
        sed -i "/^$shell_id/d" "$config_file"
        exit 0
      fi
    ;;
    "--get" )
      if [ "$#" == 1 ] ; then
        grep "^$shell_id " "$config_file" | sed "s/^$shell_id //"
        exit 0
      fi
    ;;
    "--test" )
      echo "ensconfig"
      exit 0
    ;;
  esac

fi

echo "Sets or gets the identity configuration for a user which is shared by multiple users."$'\n'"$usage"
exit 1
