#!/bin/bash
set -e

function usage {
	cat <<USAGE
configure PROJECT
PROJECT = libcob-ocesql mconnect webssh
USAGE
}

function write_deb {
	# $1: package name
	# $2: compile_typ
	cat <<ANY_DEB >debian/$1.conf
# generated by configure
compile_type=$2
target_type=DEB
ANY_DEB
}

function write_changelog {
	# $1: package name
	cat <<CHANGELOG >debian/$1.changelog
projects (%VERSION%-%BUILD%) unstable; urgency=medium
  * generated by configure
 -- Michael Wagner <info@wagnertech.de>  Fri, 05 Dec 2025 20:03:04 +0100
CHANGELOG
}

function write_eclipse_control {
	# $1: package name
	cat <<CONTROL >debian/$1.control
Source: projects
Section: main
Priority: optional
Maintainer: Michael Wagner <michael@wagnertech.de>
Build-Depends: git, mbuild
 
Package: $1
Architecture: _DEB_HOST_ARCH
Depends: $2
Description: http://eclipse.org
CONTROL
}

function write_eclipse_cp {
	# $1: package name
	cat <<CP >debian/$1.cp
#!/bin/bash
set -e

mkdir -p \$1/opt/$1/
cp -a Downloads/eclipse/* \$1/opt/$1/
CP
}

function write_eclipse_postinst {
	# $1: package name
	cat <<POSTINST >debian/$1.postinst
#!/bin/bash
set -e

for user in user nutzer kurs; do
	if [ -d /home/\$user ]; then
		echo "Install eclipse for user \$user"
		pushd /home/\$user >/dev/null

			if [ -d Schreibtisch ]; then
				pushd Schreibtisch >/dev/null
					su \$user -c "ln -sf /opt/eclipse-cpp/eclipse ."
				popd >/dev/null
			fi

			if [ -d Desktop ]; then
				pushd Desktop >/dev/null
					su \$user -c "ln -sf /opt/eclipse-cpp/eclipse ."
				popd >/dev/null
			fi
		popd >/dev/null
	fi
done
POSTINST
}

function write_eclipse_prepare {
	# $1: package name
	# $2: ECLIPSE_PATTERN
	cat <<PREPARE >debian/$1.prepare
#!/bin/bash
set -e

debian/eclipse.prepare $2
PREPARE
}

function configure_eclipse {
	# $1: package name
	# $2: ECLIPSE_PATTERN
	# $3: additional dependencies

	write_deb $1 NONE
	write_changelog $1
	write_eclipse_control $1 "$3"
	write_eclipse_cp $1
	chmod 755 debian/$1.cp
	write_eclipse_postinst $1
	chmod 755 debian/$1.postinst
	write_eclipse_prepare $1 $2
	chmod 755 debian/$1.prepare
	mconfigure -V $1
}

if [ -z "$1" ]; then
	usage
	exit 7
fi

case $1 in

eclipse-cpp)
	configure_eclipse eclipse-cpp "eclipse-cpp*.tar.gz" "build-essential,gdb"
	;;
	
eclipse-php)
	configure_eclipse eclipse-php "eclipse-php*.tar.gz" php
	;;
	
libcob-ocesql)
	if [ -z "$2" ]; then
		echo "supply version as 2nd parameter"
		exit 131
	fi
	write_deb libcob-ocesql ANY
	mconfigure -v $2 libcob-ocesql
	;;

mconnect)
	write_deb mconnect ANY
	mconfigure mconnect
	;;

webssh)
	write_deb webssh ANY
	mconfigure -V webssh
	;;

*)
	echo "Invalid project."
	usage
	exit 25
	;;
esac

