#!/usr/bin/env bash

help()
{
    printf "Usage: tracker-changes <sincehash> <dir> [verbose]\n"
    exit 2
}

main()
{
    hashMessage=$(git show --pretty=format:"%s" -s $sinceHash)
    hashISO8601Date=$(git show --pretty="%aI" -s $sinceHash)
    sinceHashStats=$(git diff --stat main $sinceHash $dir | tail -1)
    headHash=$(git show --pretty=format:"%H" -s main | cut -c1-11)
    headMessage=$(git show --pretty=format:"%s" -s main)


    echo "Changes to '$dir' from $sinceHash ('$hashMessage') to $headHash ('$headMessage'):"
    echo
    echo "$sinceHashStats"
    echo

    declare -A trackerIssues
    for f in $(git diff --name-only main $sinceHash $dir); do
        if [ $verbose = true ]; then echo "Checking file: $f"; fi
        #See https://git-scm.com/docs/pretty-formats for list of format options.
        if [ $verbose = true ]; then echo git log --pretty=format:"%at%x09%as%x09%H%x09%s" --since="$hashISO8601Date" -p -s --graph main -- "$f"; fi
        historyLines=$(git log --pretty=format:"%at%x09%as%x09%H%x09%s" --since="$hashISO8601Date" -p -s main -- "$f")
        
        # while loop better than for since it only temporarily changes IFS.
        #IFS=$'\n'
        #for h in $(git log --pretty=format:"%at%x09%as%x09%H%x09%s" -p -s -- "$f"); do
        while IFS=$'\n' read -r commit; do
            if [ $verbose = true ]; then echo $commit; fi
            IFS=$'\t' read -r -a strings <<< "$commit"
            if [ $verbose = true ]; then echo "  Found commit: ${strings[2]}: ${strings[3]}"; fi
            commitMessageFirstToken=$(echo ${strings[3]} | sed -e 's/\s.*$//')
            if [ $verbose = true ]; then echo "First token: $commitMessageFirstToken"; fi
            if [ $commitMessageFirstToken != "Merge" ] && [ $commitMessageFirstToken != "NOBUG:" ]; then
                trackerIssues[${strings[2]}]=${strings[3]}
            fi
        done <<< "$historyLines"  
    done
    if [ $verbose = true ]; then
        echo "...done."
        echo
    fi
    echo "Found ${#trackerIssues[@]} commits affecting '$dir' between $sinceHash ('$hashMessage') and $headHash ('$headMessage'):"
    echo
    #printf '%s\n' "${trackerIssues[@]}"
    #for i in ${trackerIssues[@]}; do echo $i; done
    for i in "${!trackerIssues[@]}";do 
        #printf "Hash: %s\nCommit message: %s\n" "$i" "${trackerIssues[$i]}";
        printf "Hash: %s\n" "$i";
        echo '  'https://github.com/moodle/moodle/commit/"$i"
        mdl=$(echo ${trackerIssues[$i]} | sed -e 's/\s.*$//')
        echo '  'https://tracker.moodle.org/browse/"$mdl"
    done    
}

#sinceHash="fe7aff80932"
#dir="mod/lti"
#verbose=false
sinceHash="${1:-}"
dir="${2:-}"
verbose="${3:-false}"

if [ -z "$sinceHash" ] || [ -z "$dir" ]; then
    help
fi

main



