#!/bin/sh
#
# $NetBSD: INSTALL,v 1.5 2004/07/10 23:23:45 salo Exp $

if [ X"${2}" != XPOST-INSTALL ]
then
	exit 0
fi

PKG_PREFIX="${PKG_PREFIX-/usr/pkg}"
PATH="${PKG_PREFIX}/sbin":"${PATH}"
NEW_CONF_EXAMPLE="${PKG_PREFIX}/share/examples/wwwoffle.conf"

# Allow ${CONFDIR} to be set in the environment, so that this unsubstituted
# script can be run directly from the "pkgsrc" subdirectory via `make finish'.
if [ ! -f "${CONFDIR}"/wwwoffle.conf ]
then
	CONFDIR="@PKG_SYSCONFDIR@"
fi

if [ ! -d "${CONFDIR}" ]
then
	mkdir -p "${CONFDIR}"
fi

# If there's no configuration file in the new ${PKG_SYSCONFDIR}, search
# possible former locations for the old file. If none found, install a
# fresh one.
if [ ! -f "${CONFDIR}/wwwoffle.conf" ]
then
	if [ -f "${PKG_PREFIX}/etc/wwwoffle.conf" ]
	then
		conf_candidates="${PKG_PREFIX}/etc/wwwoffle.conf"
	fi
	if [ -f /etc/wwwoffle.conf ]
	then
		conf_candidates="$conf_candidates /etc/wwwoffle.conf"
	fi
	OLD_CONF="$(ls -rt $conf_candidates | tail -1)"
	if [ -n "$OLD_CONF" ]
	then
		cp "${OLD_CONF}" "${CONFDIR}/wwwoffle.conf"
	else
		cp "${NEW_CONF_EXAMPLE}" "${CONFDIR}/wwwoffle.conf"
	fi
fi

# The "wwwoffle-upgrade-config" script needs the template to be in ${CONFDIR}.
if [ ! -f "${CONFDIR}/wwwoffle.conf.install" ]
then
	cp "${NEW_CONF_EXAMPLE}" "${CONFDIR}/wwwoffle.conf.install"
fi

# Put the real hostname in the "wwwoffle.pac" files.
for p in `find /var/wwwoffle/html -name wwwoffle.pac`
do
	cd `dirname ${p}`
	mv ${p} ${p}.dist
	sed /PROXY/s/localhost/`hostname`/ ${p}.dist > ${p}
done

# Now utilize the installed utilities to upgrade the configuration file and
# convert the cache format. Don't require "perl" just to upgrade the config,
# as there may not even be an old config file; worst case, the user will get
# warnings in "syslog" about deprecated options.
cd ${CONFDIR} && wwwoffle-upgrade-config.pl wwwoffle.conf || true
wwwoffle-convert-cache /var/wwwoffle
