#!/bin/sh -e

. /usr/share/debconf/confmodule
db_version 2.0

if dpkg --compare-versions "$2" lt-nl 2.4.0~beta2; then
    rm -f /var/www/cobbler
    ln -sf /var/lib/cobbler/webroot/cobbler /var/www/cobbler
    cp -pR /usr/share/cobbler/webroot/cobbler/* /var/lib/cobbler/webroot/cobbler/ && \
        rm -fr /usr/share/cobbler/webroot/cobbler
fi

# migrate to apache2.4
if dpkg --compare-versions "$2" le-nl 2.4.0-0ubuntu2; then
    mv /etc/apache2/conf.d/cobbler.conf /etc/apache2/conf-enabled/
fi

if ([ "$1" = "configure" ] && [ -z "$2" ]) || [ "$1" = "reconfigure" ] || [ -n "$DEBCONF_RECONFIGURE" ]; then
	# Set cobbler's password
	db_get cobbler/password || true
	password="$RET"
	hash=$(printf "cobbler:Cobbler:$password" | md5sum | awk '{print $1}')
	[ -e /etc/cobbler/users.digest ] || install -o root -g root -m 0600 /dev/null /etc/cobbler/users.digest
	htpasswd -D /etc/cobbler/users.digest "cobbler" || true
	printf "cobbler:Cobbler:$hash\n" >> /etc/cobbler/users.digest
	hash=$(printf "$password" | openssl passwd -1 -stdin)
	sed -i "s%^default_password_crypted:.*%default_password_crypted: \"$hash\"%" /etc/cobbler/settings

	db_get cobbler/server_and_next_server || true
	ipaddr="$RET"
	db_set cobbler/server_and_next_server "$ipaddr"

	if grep -qs "^next_server: *..*..*..*$" /etc/cobbler/settings; then
		sed -i "s/^next_server: *..*..*..*$/next_server: $ipaddr/" /etc/cobbler/settings
	fi
	if grep -qs "^server: *..*..*..*$" /etc/cobbler/settings; then
		sed -i "s/^server: *..*..*..*$/server: $ipaddr/" /etc/cobbler/settings
	fi

	# Enable required apache modules
	a2enmod proxy_http
	a2enmod wsgi
	a2enmod rewrite

	# Install cobbler files and web config for API
	ln -sf /var/lib/cobbler/webroot/cobbler /var/www/cobbler
	if [ ! -e /etc/apache2/conf-enabled/cobbler_web.conf ]; then
	    ln -sf /etc/cobbler/cobbler.conf /etc/apache2/conf-enabled/cobbler.conf
	fi

	# Need to restart apache to pickup web configs
	if [ -x /usr/sbin/invoke-rc.d ]; then
		invoke-rc.d apache2 restart || true
	else
		/etc/init.d/apache2 restart || true
	fi
fi

db_stop

#DEBHELPER#

exit 0
