#!/bin/bash
# Generate changelogs for all projects repositories:
# hg log -v -d ">YYYY-MM-DD" | egrep -v "^changeset:|^date:|^tag:|^files:|^user:|^description:|^parent:|^$" > Changelog
#
# Note: this script requires the use of the cdtools functions.
# ---------------------------------------------------------------------------------------------------------------------
function doHelp
{
    echo ""
    echo "Generate a Changelog for all project repositories."
    echo ""
    echo "$0 -p <proj> [-d YYYY-MM-DD]"
    echo "where"
    echo "-p <proj>    The name of the project file to source under ~/bin/changelogs."
    echo "             <proj> must match file name and contain the function doLogs()."
    echo "-d <date>    Specify the date equal to or after which changelogs should be generated."
    echo "             If no date is specified, it will be from the beginning of the current month."
}

function findProj
{
	SHF=~/bin/env/${PRJ}
	if [ ! -f $SHF ]
	then
		SHF=~/bin/env/${PRJ}.sh
		if [ ! -f $SHF ]
		then
			echo "Can't find project cdtools script: $SHF"
			exit 1
		fi
	fi
	echo "Found project cdtools script: $SHF"
}

#--------------------------------------------------------------
# Read command line arguments
#--------------------------------------------------------------
while getopts ":d:p:" Option
do
    case $Option in
    d) DATE=$OPTARG;;
    p) SCR=$OPTARG;;
    *) doHelp; exit 0;;
    esac
done

if [ "$SCR" = "" ]
then
	echo "You must specify a changelogs script to source."
	exit 1
fi
if [ ! -f ~/bin/changelogs/$SCR ]
then
	echo "~/bin/changelogs/$SCR does not exist."
	exit 1
fi

if [ "$DATE" = "" ]
then
    YEAR=`date +%Y`
    MON=`date +%m`
    DATE="$YEAR-$MON-01"
fi
CMD="hg log -v -d \">$DATE\" | egrep -v \"^changeset:|^date:|^tag:|^files:|^user:|^description:|^parent:|^$\" > Changelog"

# Source the changelogs script
. ~/bin/changelogs/$SCR
findProj 

# Setup
CWD=`pwd`
rm -rf logs
mkdir logs
cd logs
LOGDIR=`pwd`

# Call the project specific log generator
. $SHF
doLogs $LOGDIR

# Now generate the single log file
cd $LOGDIR
for file in `ls -1`
do
    if [ -s $file ]
    then
        repo=`echo $file | cut -f2 -d"."`
        hdr="Repository: $repo"

        echo "-----------------------------------------------------" >> Changelog
        echo "$hdr" >> Changelog
        echo "-----------------------------------------------------" >> Changelog

        # cat $file | sort >> Changelog
        cat $file >> Changelog
        echo "" >> Changelog
    fi
done

echo "Changelog generated: "
ls -1 $LOGDIR/Changelog
