#!/bin/sh

function print_usage(){
    cat <<END
Usage: $0 [OPTIONS] project_name
This command generate skeleton configuration files for cmake build system.

Options:
    -h: Print help message.
    -A { authors }: Authors. This will also apply to license document if
       possible.
    -B { cmake_templates_path }: Pathes which contain cmake templates.
       Pathes are splited with ';'.
       Default path is "$TEMPLATES_PATH"
    -L { GPLv2+ | LGPLv2+ | GPLv3+ | LGPLv3+ | BSD }:
       LICENSE for this project. Licence files will be copied to current
       directory. Authors and vendor will also applied if -A and -V are
       given.
       Default is "GPLv3+".
    -M { maintainer_contact}: name and email of a maintainer.
    -V { vendor }: Vendor. This will also apply to license document if
        possible.
    -e { old_spec(.in) }: Extract values from original spec or spec.in.
       This maybe handy when converting an old project to cmake-fedora.
    -i { initial_version }: Inital project version.
	Default value is "0.1.0".
    -m { project_summary }: Project summary.
    -s { git | hg | svn }: source version control.
        Default value is "git".
END
}

function set_value(){
    if [ -n "$2" ];then
	eval "$1=$2"
    fi
}

function extract_key_from_spec(){
    newValue=`grep -e "^$2:[[:space:]]*" $OPT_EXTRACT_SPEC \
    | sed -e "s/$2:[[:space:]]*//"`
    set_value $1 "$newValue"
    echo "From spec: $1: $newValue" > /dev/stderr
}

## extract_from_spec
function extract_from_spec(){
    ## PRJ_AUTHORS
    newValue=`grep -e '^\* [A-Za-z]\+ [A-Za-z]\+ [0-9]\+ [0-9]\+ .*<' $OPT_EXTRACT_SPEC\
    | sed -e 's/^\* [A-Za-z]\+ [A-Za-z]\+ [0-9]\+ [0-9]\+ \([^<]*\) *<.*/\1/' \
    | head -n 1`
    set_value PRJ_AUTHORS "$newValue"

    extract_key_from_spec PRJ_LICENSE "License"

    ## PRJ_MAINTAINER
    newValue=`grep -e '^\* [A-Za-z]\+ [A-Za-z]\+ [0-9]\+ [0-9]\+ .*<' $OPT_EXTRACT_SPEC \
	| sed -e 's/^\* [A-Za-z]\+ [A-Za-z]\+ [0-9]\+ [0-9]\+ \([^>]*>\).*/\1/' \
	| head -n 1`
    set_value PRJ_MAINTAINER "$newValue"

    extract_key_from_spec PRJ_VER_INIT "Version"
    extract_key_from_spec PRJ_SUMMARY "Summary"
    extract_key_from_spec PRJ_GROUP "Group"
    extract_key_from_spec PRJ_URL "URL"
    extract_key_from_spec RPM_SPEC_SOURCES "Source0"
}

function find_file(){
    _file=$1
    _paths=`echo $2 | xargs -d ';'`
    for _currDir in $_paths; do
	if [ -e "${_currDir}/fedora/${_file}" ];then
	    echo "${_currDir}/fedora/${_file}"
	    return
	fi
    done
}

function copy_file(){
    _dest=$2
    if [ -e ${_dest} ];then
	echo "${_dest} already exists, skip generation!" > /dev/stderr
	return 1
    fi
    _src=`find_file $1 ${TEMPLATES_PATH}`
    cp $_src $_dest
    return 0
}

function generate_file2(){
    _dest=$1
    _src=$2
    templateFileName=`basename ${_src}`".template"
    shift 2

    if copy_file ${templateFileName} ${_dest} ;then
	for var in $@; do
	    value=$(eval echo \$${var})
	    #echo var=$var value=$value
	    sed -i.bak -e "s/<${var}>/$value/" ${_dest}
	done
	rm -f ${_dest}.bak
    fi
}

function generate_file(){
    _file=$1
    shift
    generate_file2 $_file $_file $@
}


# generate_license _dest _src [[_pattern _replace] ...]
function generate_license(){
    _dest=$1
    _src=$2
    shift 2

    if copy_file ${_src} ${_dest} ;then
	_pattern=""
	_replace=""
	for _token in "$@"; do
	    #echo "_token=${_token}"
	    if [ "$_pattern" = "" ]; then
		_pattern=$_token
	    else
		_replace=$_token
		#echo "s/$_pattern/$_replace/"
		sed -i.bak -e "s/$_pattern/$_replace/" ${_dest}
		_pattern=""
		_replace=""
	    fi
	done
	rm -f ${_dest}.bak
    fi
}

function append_gitignore(){
    if ! grep -l "$1" .gitignore > /dev/null ;then
	echo "$1" >> .gitignore
    fi
}

scriptDir=`dirname $0`
#Default Values
PRJ_AUTHORS="<PRJ_AUTHORS>"
PRJ_GROUP="<PRJ_GROUP>"
PRJ_LICENSE="GPLv3+"
PRJ_LICENSE_FILES="COPYING"
PRJ_MAINTAINER="<PRJ_MAINTAINER>"
PRJ_SPEC_URL="<PRJ_SPEC_URL>"
RPM_SPEC_SOURCES="<RPM_SPEC_SOURCES>"
PRJ_SOURCE_VERSION_CONTROL="git"
PRJ_SUMMARY="<PRJ_SUMMARY>"
TEMPLATES_PATH="/usr/share/cmake/Templates;Templates;cmake-fedora/Templates;$scriptDir/../Templates"
PRJ_VENDOR="<PRJ_VENDOR>"
PRJ_VER_INIT="0.1.0"
CMAKE_FEDORA_GIT=https://git.fedorahosted.org/git/cmake-fedora.git

if [ -e /etc/cmake-fedora.conf ]; then
    source /etc/cmake-fedora.conf
fi

while getopts "hA:B:L:M:V:e:i:m:s:" opt; do
    case $opt in
	h)
	    print_usage;
	    exit 0;
	    ;;
	A)
	    PRJ_AUTHORS="$OPTARG";
	    ;;
	B)
	    TEMPLATES_PATH="$OPTARG";
	    ;;
	L)
	    PRJ_LICENSE="$OPTARG";
	    ;;
	M)
	    PRJ_MAINTAINER="$OPTARG";
	    ;;
	V)
	    PRJ_VENDOR="$OPTARG";
	    ;;
	e)
	    OPT_EXTRACT_SPEC=$OPTARG;
	    if [ ! -r ${OPT_EXTRACT_SPEC} ]; then
		echo "Error: Cannot read ${OPT_EXTRACT_SPEC}" > /dev/stderr
		exit -1
	    fi
	    extract_from_spec
	    ;;
	i)
	    PRJ_VER_INIT="$OPTARG";
	    ;;
	m)
	    PRJ_SUMMARY=$OPTARG;
	    ;;
	s)
	    PRJ_SOURCE_VERSION_CONTROL=`echo $OPTARG | sed -e 's/\(.*\)/\L\1/g'`;
	    ;;
	*)
	    ;;
    esac
done
shift $((OPTIND-1));
PRJ_NAME=$1;
if [ -z $PRJ_NAME ];then
    print_usage
    exit 1
fi

## Generate files
generate_file RELEASE-NOTES.txt  PRJ_VER_INIT

YEAR=`date +%Y`
## Copy licenses
case $PRJ_LICENSE in
    LGPLv3* )
        generate_license COPYING.LESSER lgpl-3.0.txt
	generate_license COPYING gpl-3.0.txt \
	    "<one line to give the program's name and a brief idea of what it does.>" \
	    "$PRJ_NAME - $PRJ_SUMMARY" \
	    "<year>" "$YEAR" \
	    "<name of author>" "$PRJ_AUTHORS" \
	    "<program>" "<$PRJ_NAME>"
	PRJ_LICENSE_FILES="COPYING COPYING.LESSER"
	;;

    GPLv3* )
	generate_license COPYING gpl-3.0.txt \
	    "<one line to give the program's name and a brief idea of what it does.>" \
	    "$PRJ_NAME - $PRJ_SUMMARY" \
	    "<year>" "$YEAR" \
	    "<name of author>" "$PRJ_AUTHORS" \
	    "<program>" "<$PRJ_NAME>"
	;;

    LGPLv2* )
        generate_license COPYING.LESSER lgpl-2.1.txt \
	    "<one line to give the library's name and a brief idea of what it does.>" \
	    "$PRJ_NAME - $PRJ_SUMMARY" \
	    "<year>" "$YEAR" \
	    "<name of author>" "$PRJ_AUTHORS" \
	    "Frob" "<$PRJ_NAME>" \
	    "year name of author" "$YEAR $PRJ_AUTHORS" \
	    "Yoyodyne, Inc" "$PRJ_VENDOR" \
	    "a library for tweaking knobs" "$PRJ_SUMMARY" \
	    "James Random Hacker" "$PRJ_AUTHORS"
	generate_license COPYING gpl-2.0.txt \
	    "<one line to give the program's name and a brief idea of what it does.>" \
	    "$PRJ_NAME - $PRJ_SUMMARY" \
	    "<year>" "$YEAR" \
	    "<name of author>" "$PRJ_AUTHORS" \
	    "Gnomovision" "<$PRJ_NAME>" \
	    "version 69" "version $PRJ_VER_INIT" \
	    "year name of author" "$YEAR $PRJ_AUTHORS" \
	    "Yoyodyne, Inc." "$PRJ_VENDOR" \
	    "which makes passes at compilers" "$PRJ_SUMMARY" \
	    "James Hacker" "$PRJ_AUTHORS"
	;;

    GPLv2* )
	generate_license COPYING gpl-2.0.txt \
	    "<one line to give the program's name and a brief idea of what it does.>" \
	    "$PRJ_NAME - $PRJ_SUMMARY" \
	    "<year>" "$YEAR" \
	    "<name of author>" "$PRJ_AUTHORS" \
	    "Gnomovision" "<$PRJ_NAME>" \
	    "version 69" "version $PRJ_VER_INIT" \
	    "year name of author" "$YEAR $PRJ_AUTHORS" \
	    "Yoyodyne, Inc." "$PRJ_VENDOR" \
	    "which makes passes at compilers" "$PRJ_SUMMARY" \
	    "James Hacker" "$PRJ_AUTHORS"
	PRJ_LICENSE_FILES="COPYING COPYING.LESSER"
	;;

    BSD )
	generate_license COPYING bsd-3-clauses.txt \
	    "<YEAR>" "$YEAR" \
	    "<OWNER>" "$PRJ_AUTHORS" \
	    "<ORGANIZATION>" "$PRJ_VENDOR"
	;;

    * )
	;;
esac

if [ -n "$PRJ_SOURCE_VERSION_CONTROL" ];then
    SVC=`echo $PRJ_SOURCE_VERSION_CONTROL | sed -e 's/\(.*\)/\U\1/g'`;
    MANAGE_SOURCE_VERSION_CONTROL="MANAGE_SOURCE_VERSION_CONTROL_${SVC}()"
fi

generate_file CMakeLists.txt PRJ_NAME PRJ_AUTHORS PRJ_LICENSE PRJ_LICENSE_FILES\
    PRJ_MAINTAINER PRJ_SOURCE_VERSION_CONTROL\
    MANAGE_SOURCE_VERSION_CONTROL\
    PRJ_SUMMARY PRJ_VENDOR PRJ_GROUP PRJ_SPEC_URL RPM_SPEC_SOURCES

## Generate AUTHORS
if [ ! -e AUTHORS ];then
    echo "$PRJ_AUTHORS" | xargs -d ';' -n 1 >> AUTHORS
fi

##############################
# Source Version Control
#

echo "PRJ_SOURCE_VERSION_CONTROL=$PRJ_SOURCE_VERSION_CONTROL"
case $PRJ_SOURCE_VERSION_CONTROL in
    git )
	## GIT
	if [ ! -r .gitignore ];then
	    touch .gitignore
	fi

	append_gitignore '*NO_PACK*'
	append_gitignore '*~'
	append_gitignore '**/CMakeFiles/'
	append_gitignore '**/_CPack_Packages/'
	append_gitignore '**/Testing/'
	append_gitignore '**/BUILD/'
	append_gitignore '**/BUILDROOT/'
	append_gitignore '**/RPMS/'	
	append_gitignore '**/SPECS/'
	append_gitignore '**/SOURCES/'
	append_gitignore '**/SRPMS/'
	append_gitignore '**/FedPkg/'
	append_gitignore 'CMakeCache.txt'
	append_gitignore 'cmake_*install.cmake'
	append_gitignore 'CPack*Config.cmake'
	append_gitignore 'CTestTestfile.cmake'

	if [ ! -d Modules ];then
	    if [[ -d .git ]];then
		git submodule add ${CMAKE_FEDORA_GIT}
	    else
		git clone ${CMAKE_FEDORA_GIT}
	    fi		
	    if [[ -d cmake-fedora/Modules ]]; then
		ln -s cmake-fedora/Modules .
	    fi
	fi
	;;
    *)
	;;
esac

