#!/bin/sh

# Directories
prefix=/usr
datarootdir=${prefix}/share
datadir=/usr/share
templatedir=/usr/share/vine-manual-skel/template
CWD=$PWD

# My name
MYNAME=`basename $0`

# print usage
print_usage()
{
cat << EOM
${MYNAME}	Initialize package of manual for Vine Linux.

Usage: ${MYNAME} [OPTION]... PACAGE-NAME

  -d, --docdir              install directory name (base name) [PACKAGE-NAME]
  -v                        version of new manual [1.0]
      --help                display help and exit
      --version             output version information and exit
EOM
}

# print version
print_version()
{
cat << EOM
${MYNAME} 0.1

Copyright (C) 2011 Project Vine.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Written by Yasumichi Akahoshi <yasumichi@vinelinux.org>
EOM
}

#
# parse arguments.
#
if [ -z "$*" ]; then
	print_usage
	exit 1
fi

while [ ! -z "$*" ]; do
	case $1 in
		-d|--docdirbase)
			DOCDIR=$2
			shift
			;;
		-v)
			DVERSION=$2
			shift
			;;
		--help)
			print_usage
			exit
			;;
		--version)
			print_version
			exit
			;;
		*)
			if [ -z "${TARGET}" ]; then
				TARGET=$1
			else
				echo "Too many targets." >&2
				echo >&2
				print_usage
				exit 1
			fi
			;;
	esac
	shift
done

#
# main
#

TARGETDIR=${CWD}/${TARGET}
YEAR=`date +%Y`
SERIESID=`scrollkeeper-gen-seriesid`
if [ -z "${DOCDIR}" ];then
	DOCDIR=${TARGET}
fi
if [ -z "${DVERSION}" ];then
	DVERSION=1.0
fi

# make new package disrectory
if [ -d ${TARGETDIR} -o -f ${TARGETDIR} ];then
	echo "Error: ${TARGETDIR} is already exists." >&2
	exit 1
fi
mkdir ${TARGETDIR}

# copy files from template
for file in `find ${templatedir} | sed -e "s|${templatedir}||"`
do
	if [ -d ${templatedir}${file} ];then
		mkdir ${TARGETDIR}${file}
	elif [ "${file##*.}" = "skel" ];then
		DESTFILE=`dirname ${file}`/`basename ${file} .skel | sed -e "s/package/${TARGET}/"`
		sed	-e "s|\@PACKAGE\@|${TARGET}|g"	  -e "s|\@PACKAGEDIR\@|${DOCDIR}|g"	\
			-e "s|\@DVERSION\@|${DVERSION}|g" -e "s|\@YEAR\@|${YEAR}|g"		\
			-e "s|\@SERIESID\@|${SERIESID}|g"					\
			${templatedir}${file} > ${TARGETDIR}/${DESTFILE}
	else
		DESTFILE=`echo ${file} | sed -e "s/package/${TARGET}/"`
		cp ${templatedir}${file} ${TARGETDIR}${file}
	fi
done

# autotoolize
cd ${TARGETDIR}
aclocal
automake -c -a
autoconf

rm -rf ${TARGETDIR}/autom4te.cache

