#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

addHeader=false

function usage {
	echo -e "Usage: $(basename $0) [OPTIONS] COMMIT"
	echo -e "       Generate patch from COMMIT."
	echo -e "       COMMIT is either:"
        echo -e "               * a number of commit"
        echo -e "               * a revision starting with r"
	echo -e ""
	echo -e "Available options:"
        echo -e "       -h: add commit msg to the beginning of the patches"
}

while getopts ":h" opt; do
	case $opt in
		h) echo "Printing headers"
                addHeader=true
		;;
		\?)
		echo "Invalid option: -$OPTARG" >&2
		usage
		exit 1
		;;
	esac
done
shift $(( OPTIND - 1 ))

if [ $# != 1 ]; then
        usage
        exit 1
fi
revision=0
if [[ $1 == r* ]];then
        revisions=$(svn log -rHEAD:${1#r} | grep -e "^r[0-9]" | cut -f1 -d" " | cut -c2-)
else
        nb_rev=$1
        nb_rev=$((nb_rev+1))
        revisions=$(svn log -l $nb_rev | grep -e "^r[0-9]" | cut -f1 -d" " | cut -c2-)
fi

i=0
prev=0
first=0
for rev in $revisions; do
        if [ $prev == 0 ]; then
                first=${rev}
                prev=${rev}
                continue
        fi
        commit_msg=$(svn log -r${prev}| sed '4q;d')
        commit_msg=${commit_msg// /_}
        commit_msg=${commit_msg//\//_}
        file_name=$(printf "%04d_r%d_%s.patch" ${i} ${prev} ${commit_msg})
        i=$((i+1))
        echo "Create path ${file_name}"
        if $addHeader; then
                svn log -r${prev} > $file_name
                svn diff -r${rev}:${prev} >> $file_name
        else
                svn diff -r${rev}:${prev} > $file_name
        fi
        prev=${rev}
done

root=$(svn info | grep "Relative URL" | cut -d"^" -f2)
files=$(svn log -r${rev}:${first} --verbose | grep "   [AM] " | awk '{print $2}' | sort -u | sed "s#${root}##" |sed "s#^/##" | sed '/^$/d')
echo $files > modified_files
