#!/bin/bash
#
# Univention Configuration Registry
#  template based generator for UMC modules
#
# SPDX-FileCopyrightText: 2011-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

set -e -u

have () {
	command -v "$1" >/dev/null 2>&1
}

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() {
	local str="$1" ikey
	for ikey in "${KEYS[@]}"
	do
		str=${str/$ikey/${!ikey}}
	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"
# shellcheck disable=SC2034
YEAR=$(date +'%Y')
NO_DEBIAN=""

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: $CATEGORYNAME)
  --keywords     module keywords (default: '$MODULEKEYWORDS)
  --package      package name
  --icon         path to SVG icon file
  --list         list available templates
  --template     name of the template (default: $TEMPLATE)
  --no-debian    do not copy debian packages files

EOF
	exit "${1:-0}"
}

find_templates () {
	for SRC_DIR in "$(readlink -f ../umc-module-templates)" /usr/share/univention-management-console-dev/umc-module-templates
	do
		[ -d "$SRC_DIR" ] && return 0
	done
	error "Template directory not found"
}
find_templates

# parse the CLI parameters
opts=$(getopt --options 'h' --longoptions 'help,name:,description:,keywords:,category:,package:,icon:,template:,list,no-debian' --name "${0##*/}" -- "$@") ||
	usage 2
eval set -- "$opts"
while [ $# -ge 1 ]
do
	case "$1" in
		--help|-h)
			usage 0
			;;
		--name)
			# shellcheck disable=SC2034
			MODULENAME="$2"
			shift 2
			;;
		--description)
			# shellcheck disable=SC2034
			MODULEDESC="$2"
			shift 2
			;;
		--keywords)
			# shellcheck disable=SC2034
			MODULEKEYWORDS="$2"
			shift 2
			;;
		--category)
			# shellcheck disable=SC2034
			CATEGORYNAME="$2"
			shift 2
			;;
		--package)
			PACKAGENAME="$2"
			shift 2
			;;
		--icon)
			ICONFILE="$2"
			shift 2
			;;
		--template)
			TEMPLATE="$2"
			shift 2
			;;
		--list)
			echo "Available templates:"
			exec find "$SRC_DIR" -mindepth 1 -maxdepth 1 -type d -not -name debian -printf '  %f\n'
			;;
		--no-debian)
			NO_DEBIAN="yes"
			shift 1
			;;
		--)
			shift
			break
			;;
		*)
			error "Internal error: $*"
			;;
	esac
done

SRC="$SRC_DIR/$TEMPLATE"
[ -d "$SRC" ] ||
	err "unknown template $TEMPLATE"

MODULEID="${1:?module ID missing}"

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 findType in d f
do
	find "$moduleDir" -type "$findType" | sort -r | while read -r ipath; do
		jpath=$(replace_var "$ipath")
		[ "$ipath" != "$jpath" ] && mv "$ipath" "$jpath"
	done
done

# replace file content
sedParam=""
for ikey in "${KEYS[@]}"; do
	sedParam+="s/$ikey/${!ikey}/g; "
done
find "$moduleDir" -type f -exec sed -i "$sedParam" {} +

# 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 have inkscape
	then
		inkscape -C -w $i -h $i -e "$out" "$icon"
	elif have convert
	then
		convert -background none "$icon" -resize "${i}x${i}" -define png:exclude-chunk=date,time "$out"
	else
		warn "Could not find inkscape or ImageMagick to convert SVG icon to PNG format."
	fi
done

