#!/bin/bash
# -*- coding: utf-8 -*-
#
# Univention Configuration Registry
#  template based generator for UMC modules
#
# Copyright 2011-2014 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

usage () {
	cat <<EOF
usage: $(basename $0) [<options>...] <moduleID> [<destinationDir>]

destination dir:
  If not given, it defaults to the current working directory.

options:
  --name         displayed name of the module
  --description  verbose module description (shown as tooltip)
  --category     category id (default: system)
  --keywords     module keywords (default: 'dummy)
  --package      package name
  --icon         path to SVG icon file
  --list         list available templates
  --template     name of the template (default: grid_with_detailpage)
  --no-debian    do not copy debian packages files

EOF
}

if [ $# -eq 0 -o "$1" == "--help" -o "$1" == "-h" ]; then
	usage
	exit 1
fi

function err() {
	echo
	echo "ERROR: $@"
	echo "... aborting"
	echo
	exit 1
}

function warn() {
	echo
	echo "WARNING: $@"
	echo
}

KEYS=(MODULEID MODULENAME MODULEDESC MODULEKEYWORDS PACKAGENAME CATEGORYNAME YEAR)

function replace_var() {
	str="$1"
	for ikey in ${KEYS[@]}; do
		eval "ival=\${$ikey}"
		str=${str/$ikey/$ival}
	done
	echo "$str"
}

# default values
MODULEID=dummy
MODULENAME="Dummy module"
MODULEDESC="This is a dummy module"
MODULEKEYWORDS="dummy"
PACKAGENAME=""
CATEGORYNAME="system"
ICONFILE=""
DESTDIR="$PWD"
TEMPLATE="grid_with_detailpage"
SRC_DIR="/usr/share/univention-management-console-dev/umc-module-templates"
YEAR=$(date +'%Y')
NO_DEBIAN=""

# parse the CLI parameters
for iparam in "$@"; do
	case "$iparam" in
		--name)
			MODULENAME="$2"
			shift 2
			;;
		--description)
			MODULEDESC="$2"
			shift 2
			;;
		--keywords)
			MODULEKEYWORDS="$2"
			shift 2
			;;
		--category)
			CATEGORYNAME="$2"
			shift 2
			;;
		--package)
			PACKAGENAME="$2"
			shift 2
			;;
		--icon)
			ICONFILE="$2"
			shift 2
			;;
		--template)
			TEMPLATE="$2"
			shift 2
			;;
		--list)
			echo "Available templates:"
			(cd $SRC_DIR && find -maxdepth 1 -type d ! -name debian -a ! -name "." | sed 's,./,  ,')
			exit 0
			;;
		--no-debian)
			NO_DEBIAN="yes"
			shift 1
			;;
	esac
done

SRC="$SRC_DIR/$TEMPLATE"
if [ ! -d "$SRC" ]; then
	echo "error: unknown template $TEMPLATE"
	exit 1
fi

MODULEID="$1"
if [ -z "$MODULEID" ]; then
	usage
	echo "error: module ID missing!"
	exit 1
fi

if [ $# -ge 2 ]; then
	DESTDIR=$(readlink -f "$2")
fi

# default values
if [ -z "$PACKAGENAME" ]; then
	PACKAGENAME=univention-management-console-module-$MODULEID
fi

# copy dummy module 
moduleDir="$DESTDIR/$PACKAGENAME"
[ -e "$moduleDir" ] && err "The destination directory already exists: $moduleDir"
cp -r "$SRC" "$moduleDir"
[ -z "$NO_DEBIAN" ] && cp -r "$SRC_DIR/debian" "$moduleDir"

# fix directory and file names
for findParam in "-type d" "-type f"; do
	find "$moduleDir" $findParam | sort -r | while read ipath; do
		jpath=$(replace_var "$ipath")
		[ "$ipath" != "$jpath" ] && mv "$ipath" "$jpath"
	done
done

# replace file content
sedParam=""
for ikey in ${KEYS[@]}; do
	eval "ival=\${$ikey}"
	sedParam="${sedParam}s/$ikey/$ival/g; "
done
sed -i "$sedParam" $(find "$moduleDir" -type f)

# create empty changelog
cd "$moduleDir"
dch --create --package "$PACKAGENAME" --newversion 0.1.0-1 --distribution unstable "Initial release (Bug #XXXXXX)"

# custom icon file
icon="$moduleDir/umc/icons/scalable/$MODULEID.svgz"
if [ -n "$ICONFILE" ]; then
	# we got a custom icon file... remove the default and copy the custom icon
	ext=${ICONFILE##*.}
	rm -f "$icon"
	icon="${icon%.*}.$ext"
	cp "$ICONFILE" "$icon"
fi

# scale icons
for i in 50 16; do
	out="$moduleDir/umc/icons/${i}x${i}/$MODULEID.png"
	mkdir -p "${out%/*}"
	if which inkscape > /dev/null 2>&1; then
		# inkscape is available
		inkscape -C -w $i -h $i -e "$out" "$icon"
	elif which convert > /dev/null 2>&1; then
		# ImageMagick is available
		convert -background none "$icon" -resize "${i}x${i}" "$out"
	else
		warn "Could not find inkscape or ImageMagick to convert SVG icon to PNG format."
	fi
done

