#!/usr/bin/env bash

##
# twgit
#
# git clone git@github.com:Twenga/twgit.git [path]
# cd [path]
# Install: sudo make install --always-make
# ou /bin/bash [path]/twgit
#
# Sur le modèle de http://github.com/nvie/gitflow

# Dans ~/.bash_profile :
# function get_git_branch {
#         local branch=$(git branch --no-color 2>/dev/null | grep -P '^\*' | sed 's/* //')
#         if [ ! -z "$branch" ]; then
#                 echo -n " \[\e[1;30m\]git\[\e[1;35m\]$branch"
#                 [ `git status --porcelain --ignore-submodules=all | wc -l` -ne 0 ] && echo '*'
#         fi
# }
# Puis :
#    export PROMPT_COMMAND='PS1="\[\e[0;32m\]\h:\w$(get_git_branch)\[\e[1;32m\]\\$\[\e[m\] "'
#
#
#
# Copyright (c) 2011 Twenga SA
# Copyright (c) 2012-2013 Geoffroy Aubry <geoffroy.aubry@free.fr>
# Copyright (c) 2013 Sebastien Hanicotte <shanicotte@hi-media.com>
#
# 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.
#
# @copyright 2011 Twenga SA
# @copyright 2012-2013 Geoffroy Aubry <geoffroy.aubry@free.fr>
# @copyright 2013 Sebastien Hanicotte <shanicotte@hi-media.com>
# @license http://www.apache.org/licenses/LICENSE-2.0
#



##
# Configuration
#

# Pre config:
# Absolute path of the top-level directory of the current user repository:
TWGIT_USER_REPOSITORY_ROOT_DIR="$(git rev-parse --show-toplevel 2>/dev/null)"

# Includes :
path="$0"; while [ -h "$path" ]; do path="$(readlink "$path")"; done
shared_config_file="$(dirname $path)/conf/twgit.sh"
template_config_file="${shared_config_file%.sh}-dist.sh"
local_config_file="${TWGIT_USER_REPOSITORY_ROOT_DIR:-.}/.twgit"
if [ ! -f "$shared_config_file" ]; then
    echo "/!\\ Config file not found: '$shared_config_file'"
    echo "Try to copy '$template_config_file' to '$shared_config_file' and configure it."
    exit 1
fi

# Load default config:
. $template_config_file

# Load user config with color overloading management:
declare -A colors_copy
for key in "${!CUI_COLORS[@]}"; do colors_copy[$key]="${CUI_COLORS[$key]}"; done
. $shared_config_file
for key in "${!colors_copy[@]}"; do
    [ -z "${CUI_COLORS[$key]-}" ] && CUI_COLORS[$key]="${colors_copy[$key]}"
done

# Load repository config with color overloading management:
if [ -f "$local_config_file" ]; then
    for key in "${!CUI_COLORS[@]}"; do colors_copy[$key]="${CUI_COLORS[$key]}"; done
    . $local_config_file
    for key in "${!colors_copy[@]}"; do
        [ -z "${CUI_COLORS[$key]-}" ] && CUI_COLORS[$key]="${colors_copy[$key]}"
    done
fi

. $TWGIT_INC_DIR/common.inc.sh

# Post config:
# TWGIT_USER_REPOSITORY_ROOT_DIR is absolute path of the top-level directory of the current user repository
TWGIT_FEATURES_SUBJECT_PATH="$TWGIT_USER_REPOSITORY_ROOT_DIR/$TWGIT_FEATURES_SUBJECT_FILENAME"



##
# Duplication des flux à des fins d'historisation
#
log_date="$(date "+%Y-%m-%d %H:%M:%S")"
log_call="$0 $@"

# Log errors:
printf -- "$TWGIT_HISTORY_SEPARATOR" "$log_date" "$log_call" >> $TWGIT_HISTORY_ERROR_PATH
PIPE_ERROR=$TWGIT_TMP_DIR/twgit_$$_error.tmp
mkfifo "$PIPE_ERROR"
tee -a <$PIPE_ERROR $TWGIT_HISTORY_ERROR_PATH &
exec 2>&-
exec 2>$PIPE_ERROR

# Log display:
printf -- "$TWGIT_HISTORY_SEPARATOR" "$log_date" "$log_call" >> $TWGIT_HISTORY_LOG_PATH
PIPE_LOG=$TWGIT_TMP_DIR/twgit_$$_log.tmp
mkfifo "$PIPE_LOG"
tee -a <$PIPE_LOG $TWGIT_HISTORY_LOG_PATH &
exec 1>&-
exec 1>$PIPE_LOG

# Clean on exit:
trap "rm -f $PIPE_LOG $PIPE_ERROR" EXIT ERR



##
# Affiche l'aide
#
# @tested_by TwgitHelpTest
#
function usage () {
    echo; CUI_displayMsg help 'Usage:'
    CUI_displayMsg help_detail '<b>twgit <command> [<action>]</b>'
    CUI_displayMsg help_detail '    Always provide branch names without any prefix:'
    CUI_displayMsg help_detail "      – '$TWGIT_PREFIX_FEATURE', '$TWGIT_PREFIX_DEMO', '$TWGIT_PREFIX_RELEASE', '$TWGIT_PREFIX_HOTFIX', (tag) '$TWGIT_PREFIX_TAG'"

    echo; CUI_displayMsg help 'Available commands are:'
    CUI_displayMsg help_detail '<b>feature</b>   Manage your feature branches.'
    CUI_displayMsg help_detail '<b>demo</b>      Manage your demo branches.'
    CUI_displayMsg help_detail '<b>release</b>   Manage your release branches.'
    CUI_displayMsg help_detail '<b>hotfix</b>    Manage your hotfix branches.'
    CUI_displayMsg help_detail '<b>tag</b>       Manage your tags.'
    echo
    CUI_displayMsg help_detail '<b>clean</b>     Help to remove branches no longer tracked.'
    CUI_displayMsg help_detail '<b>init <tagname> [<url>]</b>'
    CUI_displayMsg help_detail '          Initialize git repository for twgit:'
    CUI_displayMsg help_detail '            – git init if necessary'
    CUI_displayMsg help_detail "            – add remote $TWGIT_ORIGIN <b><url></b> if necessary"
    CUI_displayMsg help_detail "            – create '$TWGIT_STABLE' branch if not exists, or pull '$TWGIT_ORIGIN/$TWGIT_STABLE'"
    CUI_displayMsg help_detail "              branch if exists"
    CUI_displayMsg help_detail '            – create <b><tagname></b> tag on HEAD of stable, e.g. 1.2.3, using'
    CUI_displayMsg help_detail '              major.minor.revision format. '
    CUI_displayMsg help_detail "              Prefix '$TWGIT_PREFIX_TAG' will be added to the specified <b><tagname></b>."
    CUI_displayMsg help_detail '          A remote repository must exists.'
    CUI_displayMsg help_detail '<b>update</b>    Force update twgit check.'
    CUI_displayMsg help_detail '<b>[help]</b>    Display this help.'
    echo; CUI_displayMsg help 'See also:'
    CUI_displayMsg help_detail "Try '<b>twgit <command> [help]</b>' for more details."

    echo; CUI_displayMsg help 'About:'
    CUI_displayMsg help_detail "<b>Contact</b>                 https://github.com/Twenga/twgit"
    CUI_displayMsg help_detail "<b>Git repository</b>          git@github.com:Twenga/twgit.git"
    local version=$(cd $TWGIT_ROOT_DIR && git describe)
    CUI_displayMsg help_detail "<b>Version</b>                 $version"
    local last_update_timestamp=$(getLastUpdateTimestamp "$TWGIT_UPDATE_PATH")
    local last_update_date="$(getDateFromTimestamp "$last_update_timestamp")"
    local next_update_timestamp=$(( $last_update_timestamp + $TWGIT_UPDATE_NB_DAYS * 86400 ))
    local next_update_date="$(getDateFromTimestamp "$next_update_timestamp")"
    CUI_displayMsg help_detail "<b>Last check for update</b>   $last_update_date"
    CUI_displayMsg help_detail "<b>Next check for update</b>   $next_update_date"
    echo
}

##
# Action déclenchant l'affichage de l'aide.
#
# @tested_by TwgitHelpTest
#
function cmd_help () {
    usage;
}

##
# Appelle l'action demandée ("cmd_$2") sur la commande spécifiée ($1).
# Les paramètres surnumérères sont passés à la commande.
#
# @param string $1 commande demandée
# @param string $2 nom de l'action demandée, 'help' par défaut
#
function main () {
    # load command:
    if [ ! -z "$1" ]; then
        local command="$1"; shift
        guess_dyslexia "$command" && command="$RETVAL"
        local command_file="$TWGIT_INC_DIR/twgit_$command.inc.sh";
        if [ "$command" = 'help' ]; then
            usage; exit 0
        elif [ "$command" = 'update' ]; then
            autoupdate 'force'; exit 0
        elif [ "$command" = 'clean' ]; then
            clean_branches; exit 0
        elif [ "$command" = 'init' ]; then
            init "$@"; exit 0
        elif [ ! -e "$command_file" ]; then
            CUI_displayMsg error "Command not found: '$command'"
            usage
            exit 1
        else
            . "$command_file"
        fi
    fi

    # run the specified action:
    local action='help'
    if [ ! -z "$1" ]; then
        action="$1"; shift
    fi
    guess_dyslexia "$action" && action="$RETVAL"
    local action_func_name="cmd_$action"
    if ! type "$action_func_name" >/dev/null 2>&1; then
        CUI_displayMsg error "Unknown action: '$action'"
        usage
        exit 1
    else
        [ "$action" != 'help' ] && assert_git_repository
        $action_func_name "$@"
    fi
}

[ "$1" != "update" ] && [ "$TWGIT_UPDATE_AUTO" = "1" ] && autoupdate 'no-force' $*
assert_git_configured
assert_connectors_well_configured
main "$@"
