#!/bin/ksh93

LIC='[-?$Id$]
[-copyright?Copyright (c) 2013 Jens Elkner. All rights reserved.]
[-license?CDDL 1.0]'

SDIR=$( cd ${ dirname $0; }; printf "$PWD" )
typeset -r FPROG=${.sh.file}
typeset -r PROG=${FPROG##*/}

for H in log.kshlib man.kshlib ; do
	X=$SDIR/$H
	[[ -r $X ]] && . $X && continue
	X=$SDIR/../etc/$H
	[[ -r $X ]] && . $X && continue
	X=${ whence $H ; }

	[[ -z $X ]] && print -u2 "$H nicht gefunden - Abbruch." && exit 1
	. $X
done
unset H

typeset -T ApacheEnv_t=(
	typeset -h 'ServiceName der default httpd Instanz' svc=''
	typeset -h 'Apache Version' vers=''
	typeset -h 'Apache httpd Install-Root-Ordner' root=''
	typeset -h 'Name des ZFS, unter welchem das datadir angelegt werden soll, falls noch nicht vorhanden.' zfsbase=''
	typeset -h 'Das Basisverzeichnis, in welches per default das conf, sites und logs Verzeichnis kommt.' basedir='/data/web'
	typeset -h 'Default Web-Daten-Ordner (i.d.R. /var/apache2/$VERS)' defdatadir=''
	typeset -h 'Web-Daten-Ordner. Default: /data/web/sites' datadir="${_.basedir}/sites"
	typeset -h 'Default Config-Ordner (i.d.R. /etc/apache2/$VERS/)' defcfgdir=''
	typeset -h 'Config-Ordner. Default: /data/web/sites/conf/' cfgdir="${_.datadir}/conf"
	typeset -h 'Default Logfile-Ordner (i.d.R. /var/apache2/$VERS/logs)' deflogdir=''
	typeset -h 'Logfile-Ordner (bei uns /data/web/log an /var/log/httpd gemountet). Default: /var/log/httpd' logdir='/var/log/httpd'
	typeset -h 'User name, dem die Config-Ordner/Dateien gehören sollen. Default: webadm' owner='webadm'
	typeset -h 'Gruppe, der die Config-Ordner/Dateien gehören sollen. Default: staff' group='staff'
	typeset -h 'Das aktuelle Datum (Timestamp).' date=${ date '+%Y%m%d-%H:%M:%S'; }
	typeset -ih 'Indikator, ob die relevanten HTTP-Verzeichnisse bereits gecheckt worden sind (Wert == 0 falls nicht)' dirsok=0
	typeset -ih 'Indikator, ob die relevanten HTTPd Config-Dateien überschrieben werden sollen (Wert == 1). Backup-Datei wird voher angelegt.' overwrite=0
	typeset -h 'Fully qualified domain name der website' fqdn=''
	typeset -h 'Hostname der website (erste componente des fqdn)' host=''
	typeset -ih 'Indikator, ob die neuen configs bereits geschrieben wurden' config=0
	typeset -ih 'Indikator, ob der cert Hasher bereits aktualisiert wurde' hasher=0
	typeset -ih 'Indikator, ob der service bereits aktualisiert wurde' svcok=0
	typeset -h 'Temp file' tfile=''
	typeset -ih 'HTTP port to use. Default: 80' port=80
	typeset -ih 'HTTPS port to use. Default: 443' sslport=443

	function init {
		[[ -n $1 ]] && _.setBaseDir "$1"
		_.fqdn=${ hostname; }
		_.host=${_.fqdn%%.*}
		typeset -a X=( ${ getent hosts ${_.fqdn} ; } )
		typeset H
		X[0]=${_.fqdn}
		for H in ${X[@]} ; do
			[[ $H != ${_.fqdn} && ${H//./ } != $H ]] && { _.fqdn=$H ; break ; }
		done

		if [[ ${ zonename; } != 'global' ]];then
			_.zfsbase='pool1'
		else
			H=${ zfs list pool1 2>/dev/null ; }
			[[ -z $H ]] && _.zfsbase=rpool/ || _.zfsbase=pool1/
			_.zfsbase+="${_.host}"
		fi
		_.tfile=${ mktemp /tmp/web.XXXXXX ; }
		[[ -z ${_.tfile} ]] && exit 1
	}

	function getDefaults {
		[[ -n ${_.svc} ]] && return
		typeset X=${ svcs -a | grep /http:apache | sort -b -k 3 | tail -1 ; }
		if [[ -z $X ]]; then
			Log.fatal "Es gibt keinen http:apache* Service.\nPackage /web/server/apache-22 oder höher nicht installiert?"
			exit 1
		fi
		_.svc=${X##*svc:}
		X=${ svcprop -p tm_man_httpd8/manpath ${_.svc} 2>/dev/null; }
		X=${X%/*}
		if [[ -z $X || ! -x $X/bin/64/httpd ]]; then
			X=${ pkg search -l -H -o search.match '*/bin/httpd' 2>/dev/null; }
			X=/${X%/bin/httpd}
		fi
		if [[ ! -x $X/bin/64/httpd ]]; then
			Log.fatal "Konnte ServerRoot nicht bestimmen.\nPackage /web/server/apache-22 oder höher nicht installiert?"
			exit 1
		fi
		_.root=$X
		_.vers=${X##*/}
		_.defcfgdir=/etc/apache2/${_.vers}
		_.defdatadir=/var/apache2/${_.vers}
		_.deflogdir=${_.defdatadir}/logs
		_.date=${ date '+%Y%m%d-%H:%M:%S'; }
		[[ -z ${_.basedir} ]] && _.basedir=/data/web
		[[ -z ${_.datadir} ]] && _.datadir=${_.basedir}/sites
		[[ -z ${_.logdir} ]] && _.logdir=/var/log/httpd
		[[ -z ${_.cfgdir} ]] && _.cfgdir=${_.datadir}/conf
		[[ -z ${_.owner} ]] && _.owner=webadm
		[[ -z ${_.group} ]] && _.group=staff
	}
	typeset -fh 'Sammelt die Infos (default Einstellungen) zum derzeit installierten Apache package ein' getDefaults

	function setBaseDir {
		_.basedir="${1}"
		_.datadir="${1}/sites"
		_.cfgdir="${1}/sites/conf"
	}
	typeset -fh 'Setzt basedir auf $1 und paßt datadir als auch cfgdir entsprechend an' setBaseDir
)

Man.addFunc copyTempFile '' '[+NAME?copyTempFile - kopiert die Datei ${CFG.tfile} an die angegebene Stelle]
[+DESCRIPTION?Kopiert die Datei ${CFG.tfile} nach \afile\a, ändert den Besitzer nach ${CFG.owner}:${CFG.group} und deren Rechte auf den angegebenen \amode\a. Ist kein mode angegeben, wird \b0644\b stattdessen verwendet.]
\n\n\afile\a [\amode\a]
'
function copyTempFile {
	[[ ! -r ${CFG.tfile} ]] && return
	Log.info "Schreibe $1 ..."
	+ cp ${CFG.tfile} "$1"
	+ chown ${CFG.owner}:${CFG.group} "$1"
	typeset MODE="$2"
	[[ -z ${MODE} ]] && MODE=0644
	+ chmod ${MODE} "$1"
}

Man.addFunc checkMethodPatch '' '[+NAME?checkMethodPatch - SMF method file check]
[+DESCRIPTION?Prüft ob das originale Apache SMF method script bereits gegen unser eigenes ausgetauscht wurde. Falls nicht, wird dies nachgeholt (und das alte mit der Erweiterung .orig gespeichert).]
'
function checkMethodPatch {
	typeset SUFFIX=${CFG.vers//.} \
	DST="/lib/svc/method/http-apache${SUFFIX}" \
	SRC="${SDIR}/http-apache22"

	if [[ ! -r ${SRC} ]]; then
		Log.warn "${SRC} nicht gefunden. ${DST} ist buggy und führt möglicherweise dazu, daß der httpd nicht gestartet werden kann!"
		return
	fi
	if [[ ! -r ${DST} ]]; then
		Log.warn "Huch: ${DST} kann nicht glesen werden. Ist das Apache package nicht korrekt installiert?"
		return
	fi
	cmp -s "${SRC}" "${DST}" && return
	# files differ
	[[ ! -e ${DST}.orig ]] && + cp -p "${DST}" "${DST}.orig"
	Log.info "Kopiere ${SRC} nach ${DST} ..."
	+ cp "${SRC}" "${DST}"
}

Man.addFunc checkDirs '' '[+NAME?checkDirs - Check wichtiger Verzichnisse auf Vorhandensein/Besitz/Rechte und ggf. Korrektur]
[+DESCRIPTION?Prüft, ob die für den httpd notwendigen ZFSs und Verzeichnisse existieren, legt selbige ggf. an, prüft und korrigiert bei Bedarf deren Besitzer und Rechte.]
'
function checkDirs {
	(( ${CFG.dirsok} )) && return

	typeset ZFS X DIR
	if [[ ! -d ${CFG.datadir} ]]; then
		ZFS="${CFG.zfsbase}${CFG.basedir}"
		X=${ zfs list -H -o mountpoint "${ZFS}" 2>/dev/null ; }
		if [[ -z $X ]]; then
			X=${ + zfs create -p -o compression=on -o atime=off \
				-o mountpoint="${CFG.basedir}" "${ZFS}" 2>&1 ; }
			(( $? != 0 )) && Log.fatal "$X" && exit 1
			+ chown ${CFG.owner}:${CFG.group} "${CFG.basedir}"
		else
			CFG.basedir=$X
			X=${ zfs list -H -o compression ${ZFS} 2>/dev/null ; }
			[[ $X == 'off' ]] && + zfs set compression=on "${ZFS}"
		fi
	fi
	typeset -a LSI
	[[ ! -d ${CFG.datadir} ]] && { + mkdir "${CFG.datadir}" || exit 1 ; }
	LSI=( ${ ls -ld "${CFG.datadir}" ; } )
	[[ ${LSI[2]} != ${CFG.owner} ]] && \
	+ chown ${CFG.owner} "${CFG.datadir}"

	for DIR in ${CFG.cfgdir} ${CFG.cfgdir}/sites ${CFG.cfgdir}/extra \
		${CFG.cfgdir}/ssl.key ${CFG.cfgdir}/ssl.crt \
		${CFG.fqdn} ${CFG.fqdn}/htdocs ${CFG.fqdn}/cgi-bin ${CFG.fqdn}/etc 
	do
		[[ ${DIR:0:1} != '/' ]] && DIR="${CFG.datadir}/${DIR}"
		if [[ ! -d ${DIR} ]]; then
			+ mkdir "${DIR}"
			+ chown ${CFG.owner} "${DIR}"
		fi
	done
	LSI=( ${ ls -ld "${CFG.cfgdir}/ssl.key" ; } )
	[[ ${LSI[0]} != 'drwxr-x---' ]] && \
		+ chmod 0750 ${CFG.cfgdir}/ssl.key
	[[ ${LSI[2]} != ${CFG.owner} || ${LSI[3]} != 'webservd' ]] && \
		+ chown ${CFG.owner}:webservd ${CFG.cfgdir}/ssl.key
	for DIR in ${CFG.logdir} ${CFG.logdir}/${CFG.fqdn} ; do
		[[ ! -d $DIR ]] && + mkdir -p "${DIR}"
		LSI=( ${ ls -ld "${DIR}" ; } )
		[[ ${LSI[2]} != 'webservd' ]] && + chown webservd "${DIR}"
	done
	# we wanna find it easier
	[[ ${CFG.logdir} != '/var/log/httpd' && ! -e /var/log/httpd ]] && \
		+ ln -s "${CFG.logdir}" /var/log/httpd
	CFG.dirsok=1
}

Man.addFunc updateSvc '' '[+NAME?updateSvc - aktualisiert die SMF properties für die default httpd Instanz]
[+DESCRIPTION?Aktualisiert die SMF properties für die default httpd Instanz und refreshed bei Bedarf selbige. Falls die benötigten Verzeichnisse und das SMF method script noch nicht gecheckt wurden, wird dies ebenso erledigt.]
[+SEE ALSO?\bcheckDirs()\b, \bcheckMethodPatch()\b, \bsvccfg\b(1M)]
'
function updateSvc {
	(( ${CFG.svcok} )) && return
	checkDirs
	checkMethodPatch
	[[ ! -f ${CFG.cfgdir}/httpd.conf ]] && createConf
	# what we want
	typeset -A cfg=(
		[httpd/enable_64bit]='true'
		[httpd/server_type]='worker'
		[httpd/startup_options]="-f ${CFG.cfgdir}/httpd.conf"
		[httpd/status_url]="http://localhost:${CFG.port}/server-status"

		[start/user]='webservd'
		[start/group]='webservd'
		[start/limit_privileges]=':default'
		[start/privileges]='basic,!proc_session,!proc_info,!file_link_any,net_privaddr'
		[start/use_profile]='false'
		[stop/user]='webservd'
		[stop/group]='webservd'
		[stop/use_profile]='false'
	)
	integer CHANGED=0
	typeset KEY VAL
	for KEY in ${!cfg[@]}; do
		VAL=${ svcprop -p ${KEY} ${CFG.svc} 2>/dev/null; }
		if [[ ${cfg[${KEY}]} != ${VAL} ]]; then
			if [[ ${KEY} == 'httpd/startup_options' ]]; then
				# quick und dirty - alles andere macht zuviel Arbeit bei Listen
   				svccfg -s ${CFG.svc} setprop \
					"${KEY}=(\"-f\" \"${CFG.cfgdir}/httpd.conf\")"
			elif [[ ${KEY} == 'httpd/status_url' ]]; then
				svccfg -s ${CFG.svc} "setprop ${KEY} = astring: ${cfg[${KEY}]}"
			else
				svccfg -s ${CFG.svc} "setprop ${KEY}=${cfg[${KEY}]}"
			fi
			(( CHANGED++ ))
		fi
	done
	X=${ svcprop -p start/environment ${CFG.svc} 2>/dev/null; }
	if [[ $X != 'LD_PRELOAD=libmtmalloc.so' ]]; then
		svccfg -s ${CFG.svc} setenv -m start LD_PRELOAD libmtmalloc.so
		(( CHANGED++ ))
	fi
	if (( CHANGED )); then
		Log.info "Initiiere ${CFG.svc} refresh ..."
		svccfg -s ${CFG.svc} refresh
	fi
	CFG.svcok=1
}

Man.addFunc getConf '' '[+NAME?getConf - setzen der Konfig-Datei entsprechend overwrite Parameter]
[+DESCRIPTION?Setzt die Variable \avname\a auf den absoluten Pfad der zu schreibenden Konfig-Datei. Ist ${CFG.overwrite} != 1, wird die entsprechende Datei zusätzlich nach \a${CFG.logdir}/file\a\b-\b\aTIMESTAMP\a kopiert. Anderenfalls wird nur \avname\a auf \a${CFG.logdir}/file\a\b-\b\aTIMESTAMP\a gesetzt, die eigentliche config Datei bleibt, wie sie ist.]
[+SEE ALSO?\bcreateConf()\b]
\n\n\avname\a \afile\a
'
function getConf {
	typeset -n CONF=$1
	CONF=${CFG.cfgdir}/$2
	if (( ${CFG.overwrite} )); then
		[[ -r ${CONF} ]] && + cp -p "${CONF}" "${CONF}-${CFG.date}"
	else
		CONF="${CONF}-${CFG.date}"
	fi
}

Man.addFunc createConf '' '[+NAME?createConf - erstellt httpd config Dateien]
[+DESCRIPTION?Erstellt die default httpd Konfig-Dateien. Ist ${CFG.overwrite} != 0, wird von evtl. vorhandenen Konfig-Dateien eine Sicherungskopie mit einem timestamp als Suffix erstellt, bevor sie überschrieben werden. Ist die Variable == 0, werden die neuen Konfig-Dateien mit einem Timestamp als Suffix gespeichert, die evtl. vorhandenen *.conf Dateien bleiben unverändert. Ebenso wird die Datei zum Erstellen der SSL hash links auf vorhandene SSL-Zertifikate aktualisiert.]
[+?Die httpd.conf enthält Einstellungen die anhand der vorhandenen CPU-Threads automatisch bestimmt werden. Sprich ändert sich deren Anzahl oder andere Parameter, ist möglicherweise ein Update der Konfig-Dateien sinnvoll.]
[+SEE ALSO?\bupdateCertHasher()\b, \bgetConf()\b, \bcopyTempFile()\b, \bpsrinfo\b(1M)]
'
function createConf {
	typeset CONF
	updateCertHasher
	(( ${CFG.config} )) && return

	getConf CONF httpd.conf
	integer SSTART=1
	integer MINSPARE=1
	integer MAXSPARE=$((2*MINSPARE))
	# max. number of simultaneous connections excl. proxy pools
	integer MAXCCON=64
	integer MAXPCON=0
	integer MAXTHREADS=128
	(( MAXCCON+=MAXTHREADS ))
	(( MAXTHREADS > MAXPCON )) && MAXPCON=${MAXTHREADS}
	integer MAXPROC=${ psrinfo | wc -l ; }
	integer CTHREADS=$((MAXCCON/MAXPROC))
	(( CTHREADS > MINSPARE )) && SSTART=1
	(( MAXSPARE < $((MAXCCON/3)) )) && MAXSPARE=$((MAXCCON/3))
	(( MAXSPARE < MINSPARE )) && MAXSPARE=${MINSPARE}
	(( CTHREADS > MAXSPARE )) && SSTART=1
	typeset TLIMIT=""
	(( CTHREADS > 64 )) && TLIMIT="ThreadLimit  ${CTHREADS}"
	cat >${CFG.tfile}<<EOF
# Das ist die minimale Konfiguration, die a priori jeder Instanz zur 
# Verfuegung stehen sollte. Weitere fuer alle sites geltende Eintraege sollten
# in conf/sites/extern.conf eingetragen werden, die VirtualServer spezifischen
# in conf/sites/\$FQDN .

ServerRoot	"${CFG.root}"
PidFile		"${CFG.logdir}/httpd.pid"
Listen		127.0.0.1:${CFG.port}

# Commonly used Modules
LoadModule		alias_module			libexec/64/mod_alias.so
#LoadModule		asis_module				libexec/64/mod_asis.so
LoadModule		autoindex_module		libexec/64/mod_autoindex.so
LoadModule		cgid_module				libexec/64/mod_cgid.so
LoadModule		deflate_module			libexec/64/mod_deflate.so
LoadModule		dir_module				libexec/64/mod_dir.so
#LoadModule		env_module				libexec/64/mod_env.so
#LoadModule		expires_module			libexec/64/mod_expires.so
#LoadModule		filter_module			libexec/64/mod_filter.so
#LoadModule		headers_module			libexec/64/mod_headers.so
#LoadModule		imagemap_module			libexec/64/mod_imagemap.so
#LoadModule		include_module			libexec/64/mod_include.so
LoadModule		log_config_module		libexec/64/mod_log_config.so
LoadModule		logio_module			libexec/64/mod_logio.so
LoadModule		mime_magic_module		libexec/64/mod_mime_magic.so
LoadModule		mime_module				libexec/64/mod_mime.so
LoadModule		negotiation_module		libexec/64/mod_negotiation.so
LoadModule		rewrite_module			libexec/64/mod_rewrite.so
LoadModule		setenvif_module			libexec/64/mod_setenvif.so

# authentication modules
#LoadModule		auth_basic_module		libexec/64/mod_auth_basic.so
#LoadModule		auth_digest_module		libexec/64/mod_auth_digest.so
#LoadModule		authn_default_module	libexec/64/mod_authn_default.so
#LoadModule		authn_file_module		libexec/64/mod_authn_file.so
#LoadModule		authn_anon_module		libexec/64/mod_authn_anon.so
#LoadModule		authn_dbd_module		libexec/64/mod_authn_dbd.so
#LoadModule		authn_dbm_module		libexec/64/mod_authn_dbm.so
#LoadModule		authnz_ldap_module		libexec/64/mod_authnz_ldap.so

# authorization modules
LoadModule		authz_host_module		libexec/64/mod_authz_host.so
#LoadModule		authz_user_module		libexec/64/mod_authz_user.so
#LoadModule		authz_groupfile_module	libexec/64/mod_authz_groupfile.so
#LoadModule		authz_default_module	libexec/64/mod_authz_default.so
#LoadModule		authz_dbm_module		libexec/64/mod_authz_dbm.so
#LoadModule		authz_owner_module		libexec/64/mod_authz_owner.so

# cache modules
#LoadModule		cache_module			libexec/64/mod_cache.so
#LoadModule		disk_cache_module		libexec/64/mod_disk_cache.so
#LoadModule		file_cache_module		libexec/64/mod_file_cache.so
#LoadModule		mem_cache_module		libexec/64/mod_mem_cache.so
#LoadModule		ldap_module				libexec/64/mod_ldap.so

# misc modules rarely used
#LoadModule		actions_module			libexec/64/mod_actions.so
# Kerberos - http://kenai.com/projects/mod-auth-gss/pages/Configuration
#LoadModule		auth_gss_module			libexec/64/mod_auth_gss.so
#LoadModule		cern_meta_module		libexec/64/mod_cern_meta.so
#LoadModule		dumpio_module			libexec/64/mod_dumpio.so
#LoadModule		dbd_module				libexec/64/mod_dbd.so
#LoadModule		ext_filter_module		libexec/64/mod_ext_filter.so
#LoadModule		ident_module			libexec/64/mod_ident.so
#LoadModule		log_forensic_module		libexec/64/mod_log_forensic.so
#LoadModule		speling_module			libexec/64/mod_speling.so
#LoadModule		substitute_module		libexec/64/mod_substitute.so
#LoadModule		suexec_module			libexec/64/mod_suexec.so
#LoadModule		unique_id_module		libexec/64/mod_unique_id.so
#LoadModule		usertrack_module		libexec/64/mod_usertrack.so
#LoadModule		version_module			libexec/64/mod_version.so
#LoadModule		vhost_alias_module		libexec/64/mod_vhost_alias.so

User		webservd
Group		webservd
ServerAdmin	root@localhost
ServerName	localhost

# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare.
# 				   StartServers * MinSpareThreads = initial number of workers.
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process.
# 				   for proxy worker this also implies the max. number of
#				   connections to the real [web] server.
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
# ServerLimit: automatically determined == MaxClients/ThreadsPerChild + 1 
StartServers		${SSTART}
${TLIMIT}
MinSpareThreads		${MINSPARE}
MaxSpareThreads		${MAXSPARE}
ThreadsPerChild		${CTHREADS}
MaxClients			${MAXCCON}
MaxRequestsPerChild	0

DefaultType				text/plain
TypesConfig				${CFG.defcfgdir}/mime.types
MIMEMagicFile			${CFG.defcfgdir}/magic
EnableMMAP				on
EnableSendfile			on
Timeout					300
KeepAlive				On
KeepAliveTimeout		5
MaxKeepAliveRequests	10000
UseCanonicalName		On
ServerTokens			Full
ServerSignature			On
HostnameLookups			On

DirectoryIndex	index.shtml index.html index.html.var

<FilesMatch "^\.ht">
	Order allow,deny
	Deny from all
</FilesMatch>

<Directory />
	Options -FollowSymLinks
	AllowOverride None
	Order deny,allow
	Deny from all
</Directory>

DocumentRoot "${CFG.defdatadir}/htdocs"
<Directory "${CFG.defdatadir}/htdocs">
	Options Indexes MultiViews -FollowSymLinks
	AllowOverride None
	Order allow,deny
	Allow from all
</Directory>

ScriptAlias /cgi-bin/printenv ${CFG.defdatadir}/cgi-bin/printenv
<Location "/cgi-bin/printenv">
	Order allow,deny
	Allow from 127.0.0.1 10.0.0.0/24
</Location>

ScriptAlias /cgi-bin/ "${CFG.defdatadir}/cgi-bin/"
<Directory "${CFG.defdatadir}/cgi-bin">
	AddHandler		cgi-script .cgi
	AllowOverride None
	Options None
	Order allow,deny
	Allow from all
</Directory>

<IfModule rewrite_module>
	RewriteLogLevel		0
	RewriteLog			"|${CFG.root}/bin/rotatelogs ${CFG.logdir}/%Y%m%d-%H%M%S-rewrite.log 2592000"
</IfModule>

LogLevel				warn
# We do not use pipe this into rotatelogs, since this file usually stays small
# and startup error are easier to detect (no need find the right log file)
ErrorLog				"${CFG.logdir}/error.log"

LogFormat				"%h %{%F %T %z}t %X %I %O %B %D %u %>s \"%r\" \"%{Referer}i\" \"%{User-Agent}i\"" extended
CustomLog				"|${CFG.root}/bin/rotatelogs ${CFG.logdir}/%Y%m%d-%H%M%S-access.log 2592000" extended env=!SSL_PROTOCOL

<IfModule cgid_module>
	ScriptSock		${CFG.logdir}/cgid.sock
</IfModule>

# Multilang error docs
Alias /error/ "${CFG.defdatadir}/error/"
<Directory "${CFG.defdatadir}/error">
	AllowOverride None
	Options IncludesNoExec
	AddOutputFilter Includes html
	AddHandler type-map var
	Order allow,deny
	Allow from all
	LanguagePriority de en fr es cs it ja ko nl pl pt-br ro sv tr
	ForceLanguagePriority Prefer Fallback
</Directory>
ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var
ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var
ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var
ErrorDocument 410 /error/HTTP_GONE.html.var
ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var
ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var
ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var
ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var
ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var
ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var
ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var
ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var
ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var
ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var

# Fancy Auto indexing
IndexOptions	FancyIndexing FoldersFirst VersionSort NameWidth=* DescriptionWidth=*
Alias /icons/ "${CFG.defdatadir}/icons/"
<Directory "${CFG.defdatadir}/icons">
	Options Indexes MultiViews
	AllowOverride None
	Order allow,deny
	Allow from all
</Directory>
AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip
AddIconByType (TXT,/icons/text.gif) text/*
AddIconByType (IMG,/icons/image2.gif) image/*
AddIconByType (SND,/icons/sound2.gif) audio/*
AddIconByType (VID,/icons/movie.gif) video/*
AddIcon /icons/binary.gif .bin .exe
AddIcon /icons/binhex.gif .hqx
AddIcon /icons/tar.gif .tar
AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv
AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip
AddIcon /icons/a.gif .ps .ai .eps
AddIcon /icons/layout.gif .html .shtml .htm .pdf
AddIcon /icons/text.gif .txt
AddIcon /icons/c.gif .c
AddIcon /icons/p.gif .pl .py
AddIcon /icons/f.gif .for
AddIcon /icons/dvi.gif .dvi
AddIcon /icons/uuencoded.gif .uu
AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl
AddIcon /icons/tex.gif .tex
AddIcon /icons/bomb.gif core
AddIcon /icons/back.gif ..
AddIcon /icons/hand.right.gif README
AddIcon /icons/folder.gif ^^DIRECTORY^^
AddIcon /icons/blank.gif ^^BLANKICON^^
DefaultIcon /icons/unknown.gif
ReadmeName README.html
HeaderName HEADER.html
IndexIgnore .ht* *~ *# HEADER* RCS CVS *,v *,t

# Include all files in the given directory
Include ${CFG.cfgdir}/sites/extern.conf

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}"

	getConf CONF sites/extern.conf
	IP=( ${ getent hosts ${CFG.fqdn} ; } )
	cat >${CFG.tfile}<<EOF
# Secure (SSL/TLS) connections
#Include ${CFG.cfgdir}/extra/ssl.conf

# Real-time info on requests and configuration
Include ${CFG.cfgdir}/extra/info.conf

# Real-time info on requests and configuration
Include ${CFG.cfgdir}/extra/mime.types.extensions

# PhP configuration - provided as an example
#Include ${CFG.cfgdir}/extra/php.conf

<IfModule !include_module>
	LoadModule	include_module		libexec/64/mod_include.so
</IfModule>
<IfModule !rewrite_module>
	LoadModule	rewrite_module		libexec/64/mod_rewrite.so
</IfModule>
#<IfModule !imagemap_module>
#	LoadModule	imagemap_module		libexec/64/mod_imagemap.so
#</IfModule>
#<IfModule !asis_module>
#	LoadModule	asis_module			libexec/64/mod_asis.so
#</IfModule>
<IfModule !expires_module>
	LoadModule	expires_module		libexec/64/mod_expires.so
</IfModule>

AddEncoding gzip .gz
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType text/javascript "access plus 7 days"
ExpiresByType text/css "access plus 7 days"
<FilesMatch "\.js\.gz$">
	ForceType text/javascript;charset=ISO-8859-1
</FilesMatch>
<FilesMatch "\.css\.gz$">
	ForceType text/css;charset=ISO-8859-1
</FilesMatch>

<Location ~ "CVS/.*">
	#AllowOverride AuthConfig Limit
	Order deny,allow
	deny from all
</Location>
<Location "/cgi-bin/printenv">
	Order deny,allow
	Deny from all
	Allow from 127.0.0.1 10.0.0.0/8
</Location>
Listen ${IP[0]}:${CFG.port}

NameVirtualHost ${IP[0]}:${CFG.port}

<IfModule ssl_module>
	SSLEngine Off
</IfModule>
<VirtualHost ${IP[0]}:${CFG.port}>
	Include ${CFG.cfgdir}/sites/${CFG.fqdn}
</VirtualHost>
<IfModule ssl_module>
	Listen ${IP[0]}:${CFG.sslport}
	<VirtualHost ${IP[0]}:${CFG.sslport}>
		SSLEngine on
		Include ${CFG.cfgdir}/sites/${CFG.fqdn}
	</VirtualHost>
</IfModule>
EOF
	copyTempFile "${CONF}"

	getConf CONF extra/manual.conf
	cat >${CFG.tfile}<<EOF
# Manuals - pkg install pkg:/web/server/apache-22/documentation
AliasMatch ^/apache/manual(?:/(?:en|de|es|fr|ja|ko|pt-br|ru))?(/.*)?$ "${CFG.root}/manual\$1"
<Directory "${CFG.root}/manual">
	Options Indexes
	AllowOverride None
	Order allow,deny
	Allow from all

	<Files *.html>
		SetHandler type-map
	</Files>

	SetEnvIf Request_URI ^/apache/manual/(de|en|es|fr|ja|ko|pt-br|ru)/ prefer-language=\$1
	RedirectMatch 301 ^/apache/manual(?:/(de|en|es|fr|ja|ko|pt-br|ru)){2,}(/.*)?$ /apache/manual/\$1\$2
	LanguagePriority de en es fr ja ko pt-br ru 
	ForceLanguagePriority Prefer Fallback
</Directory>

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}" 

	CONF=${CFG.cfgdir}/sites/pass
	if [[ ! -e $CONF ]]; then
		cat >${CFG.tfile}<<EOF
#!/bin/sh
case $1 in
	${CFG.fqdn})
		echo 'brauchenWirNich'
		;;
	*)
		echo 'UndDieErstRechtNicht'
		;;
esac
EOF
		copyTempFile "${CONF}" 0750
		+ chgrp webservd ${CONF}
	fi
	[[ ! -x ${CONF} ]] && + chmod 0750 ${CONF}

	getConf CONF extra/ssl.conf
	cat >${CFG.tfile}<<EOF
# Basic SSL Coonfiguration.
<IfModule !ssl_module>
	LoadModule		ssl_module				libexec/64/mod_ssl.so
</IfModule>
SSLRandomSeed startup file:/dev/urandom 512
SSLRandomSeed connect file:/dev/urandom 512
# Use kernel/hardware accelerated SSL
# see also Sun BluePrints: http://www.oracle.com/technetwork/server-storage/solaris10/documentation/819-5782-150147.pdf
SSLCryptoDevice pkcs11
AddType application/x-x509-ca-cert  .crt
AddType application/x-pkcs7-crl     .crl
SSLPassPhraseDialog		exec:${CFG.cfgdir}/sites/pass
SSLSessionCache			shmcb:${CFG.logdir}/ssl_scache(512000)
SSLSessionCacheTimeout	300
SSLMutex				sem
SSLCipherSuite			ALL:!ADH:!kEDH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLHonorCipherOrder on
#SSLVerifyClient require
#SSLVerifyDepth 5

SSLCertificateFile ${CFG.cfgdir}/ssl.crt/server.crt
SSLCACertificatePath ${CFG.cfgdir}/ssl.crt
<FilesMatch "\.(cgi|shtml|phtml|php)$">
	SSLOptions +StdEnvVars
</FilesMatch>
<Directory "${CFG.defdatadir}/cgi-bin">
	SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-5]" nokeepalive ssl-unclean-shutdown \
	downgrade-1.0 force-response-1.0
LogFormat   "%h %{%F %T %z}t %X %I %O %B %D %{SSL_PROTOCOL}x %{SSL_CIPHER}x %u %>s \"%r\" \"%{Referer}i\" \"%{User-Agent}i\"" extendedssl
CustomLog	"|${CFG.root}/bin/rotatelogs ${CFG.logdir}/%Y%m%d-%H%M%S-ssl.log 2592000" extendedssl env=SSL_PROTOCOL

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}"

	getConf CONF extra/proxy.conf
	cat >${CFG.tfile}<<EOF
# Basic Proxy configuration example.
<IfModule !proxy_module>
	# reverse proxy stuff
	LoadModule		proxy_module			libexec/64/mod_proxy.so
	LoadModule		proxy_http_module		libexec/64/mod_proxy_http.so
	#LoadModule		proxy_balancer_module	libexec/64/mod_proxy_balancer.so
	#LoadModule		proxy_ajp_module		libexec/64/mod_proxy_ajp.so
	#LoadModule		proxy_connect_module	libexec/64/mod_proxy_connect.so
	#LoadModule		proxy_ftp_module		libexec/64/mod_proxy_ftp.so
</IfModule>

ProxyTimeout    10
ProxyRequests   Off

# NOTE:
#  timeout .. max. time to wait for data (response) from the server. Overwrites
#             global ProxyTimeout setting. (important wrt. search queries).
#  connectiontimeout .. max. time allowed to establish a connection to the srver
#  max .. max. number of connections allowed to the server. Since the server
#         does not create more threads on demand, it is pointless to allow more
#         than MAX_THREADS. Also thus we let apache handle these situations.
#ProxyPass /DIRECTORY_TO_PROXY/ http://localhost:PORT/ \\
#	nocanon connectiontimeout=5 timeout=60 max=${MAXTHREADS}

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}"

	getConf CONF extra/info.conf
	cat >${CFG.tfile}<<EOF
<IfModule !status_module>
	LoadModule		status_module			libexec/64/mod_status.so
	LoadModule		info_module				libexec/64/mod_info.so
</IfModule>
ExtendedStatus On
<Location /server-status>
	SetHandler server-status
	Order allow,deny
	Allow from 127.0.0.1 10.0.0.0/24
</Location>
<Location /server-info>
	SetHandler server-info
	Order allow,deny
	Allow from 127.0.0.1 10.0.0.0/24
</Location>

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}"

	getConf CONF extra/dav.conf
	cat >${CFG.tfile}<<EOF
# DAV Configuration example
<IfModule !dav_module>
	LoadModule		dav_module				libexec/64/mod_dav.so
	LoadModule		dav_fs_module			libexec/64/mod_dav_fs.so
</IfModule>
DavLockDB "${CFG.logdir}/${CFG.fqdn}/DavLock"
Alias /uploads "/data/dav/${CFG.fqdn}/uploads"
<Directory "/data/dav/${CFG.fqdn}/uploads">
	Dav On
	AuthType Digest
	AuthName DAV-upload
	# htdigest -c ${CFG.cfgdir}/sites/${CFG.fqdn}-dav.passwd
	AuthUserFile ${CFG.cfgdir}/sites/${CFG.fqdn}-dav.passwd
	<LimitExcept GET POST OPTIONS>
		require user admin
	</LimitExcept>
	BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
	BrowserMatch "MS FrontPage" redirect-carefully
	BrowserMatch "^WebDrive" redirect-carefully
	BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully
	BrowserMatch "^gnome-vfs/1.0" redirect-carefully
	BrowserMatch "^XML Spy" redirect-carefully
	BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully
	BrowserMatch " Konqueror/4" redirect-carefully
</Directory>

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}"

	getConf CONF extra/mime.types.extensions
	cat >${CFG.tfile}<<EOF
# Default icons come from /icons/* 
# usually used by fancy indexing (format: 20x22px)

AddDescription "Server Side Include file" .shtml
AddType text/html .shtml

AddDescription "Adobe Portable Document Format" .pdf
AddIcon /icons/pdf.gif .pdf

AddDescription "Eclipse classpath configuration file" .classpath
AddDescription "Eclipse project configuration file" .project
AddDescription "CVS configuration file for pathes to ignore" .cvsignore
AddDescription "Ant build properties customization file" build.properties
AddDescription "Ant build file" build.xml
AddType text/xml .classpath .project .xml
AddIcon /icons/screw1.gif .classpath .cvsignore .project .properties build.xml

AddDescription "Java Archive" .jar
AddType application/x-java-archive .jar
AddDescription "Java Network Lunch Protocol Application" .jnlp
AddType application/x-java-jnlp-file .jnlp
AddDescription "Java Archive Diff" .jardiff
AddType application/x-java-archive-diff .jardiff

AddDescription "tar archive" .tar
AddDescription "GZIP compressed archive" .gz
AddDescription "GZIP compressed tar archive" .tgz
AddType application/x-gzip .gz .tgz

AddDescription "Z compressed archive" .Z
AddType application/x-compress .Z

AddDescription "Bzip2 compressed archive" .bz2
AddType application/x-bzip2 .bz2
AddIcon /icons/compressed.gif .bz2

AddDescription "Proxy Auto Configuration file" .pac
AddType application/x-ns-proxy-autoconfig .pac
AddIcon /icons/world2.gif .pac

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}"

	getConf CONF extra/userdir.conf
	cat >${CFG.tfile}<<EOF
<IfModule !userdir_module>
	LoadModule		userdir_module			libexec/64/mod_userdir.so
</IfModule>
UserDir disabled root
UserDir public_html
<Directory /home/*/public_html>
	AllowOverride FileInfo AuthConfig Limit Indexes
	Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
	<Limit GET POST OPTIONS>
		Order allow,deny
		Allow from all
	</Limit>
	<LimitExcept GET POST OPTIONS>
		Order deny,allow
		Deny from all
	</LimitExcept>
</Directory>

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}"

	getConf CONF sites/template.conf
	cat >${CFG.tfile}<<EOF
# Generiert von template.conf mittels:
# gsed -e "s/@\NODENAME@/@NODENAME@/g" -e "s/@\DOMAIN@/@DOMAIN@/g" template.conf
# 
ServerAdmin webmaster+@NODENAME@@@DOMAIN@
ServerName @NODENAME@.@DOMAIN@
ServerAlias @NODENAME@
ServerAlias @DOMAIN@

# Local access to the Apache HTTP Server Manual
Include ${CFG.cfgdir}/extra/manual.conf

# Proxy configuration - check security notes!
# Example ${CFG.cfgdir}/extra/proxy.conf

# Distributed authoring and versioning (WebDAV)
# Example ${CFG.cfgdir}/extra/dav.conf

#Include ${APACHE.cfgdir}/extra/userdir.conf

#AddOutputFilter INCLUDES .shtml
#AddHandler send-as-is asis

# 1 day logfile rotation
CustomLog	"|${CFG.root}/bin/rotatelogs ${CFG.logdir}/@NODENAME@.@DOMAIN@/%Y%m%d-%H%M%S-access.log 86400" extended env=!SSL_PROTOCOL
<IfModule ssl_module>
CustomLog	"|${CFG.root}/bin/rotatelogs ${CFG.logdir}/@NODENAME@.@DOMAIN@/%Y%m%d-%H%M%S-ssl.log 86400" extended env=SSL_PROTOCOL
</IfModule>
ErrorLog	"|${CFG.root}/bin/rotatelogs ${CFG.logdir}/@NODENAME@.@DOMAIN@/%Y%m%d-%H%M%S-error.log 86400"
<IfModule rewrite_module>
	RewriteLogLevel	0
	RewriteLog	"|${CFG.root}/bin/rotatelogs ${CFG.logdir}/@NODENAME@.@DOMAIN@/%Y%m%d-%H%M%S-rewrite.log 86400"
</IfModule>

DocumentRoot	${CFG.datadir}/@NODENAME@.@DOMAIN@/htdocs
ScriptAlias	/cgi-bin/printenv ${CFG.defdatadir}/cgi-bin/printenv
ScriptAlias	/cgi-bin/ ${CFG.datadir}/sites/@NODENAME@.@DOMAIN@/cgi-bin/

<IfModule rewrite_module>
	RewriteEngine On
	RewriteRule ^/server-	-	[L]
	
	RewriteCond %{HTTP_HOST} !=@NODENAME@.@DOMAIN@
	RewriteCond %{HTTP_HOST} !=@NODENAME@
	RewriteCond %{HTTP_HOST} !=localhost
	RewriteCond %{HTTPS} =on
	RewriteRule ^/(.*)  https://@NODENAME@.@DOMAIN@/\$1 [R=301,L]
	RewriteCond %{HTTP_HOST} !=@NODENAME@.@DOMAIN@
	RewriteCond %{HTTP_HOST} !=@NODENAME@
	RewriteCond %{HTTP_HOST} !=localhost
	RewriteCond %{HTTPS} !=on
	RewriteRule ^/(.*)  http://@NODENAME@.@DOMAIN@/\$1  [R=301,L]
</IfModule>

<Directory "${CFG.datadir}/@NODENAME@.@DOMAIN@/cgi-bin">
	Order Allow,Deny
	Allow from All
</Directory>

#ScriptAlias /cgi-bin/squid /usr/squid/libexec/cachemgr.cgi
#<Location /cgi-bin/squid>
#	order allow,deny
#	allow from 127.0.0.1 10.0.0.0/27
#</Location>

<Directory "${CFG.datadir}/@NODENAME@.@DOMAIN@/htdocs">
	AddType text/html .inc
	SetEnvIf Request_URI \.(en|de)$ prefer-language=$1
	LanguagePriority de en
	ForceLanguagePriority Prefer Fallback
	AllowOverride AuthConfig Limit
	Options +Indexes +Includes +MultiViews
	Order Allow,Deny
	Allow from All
</Directory>

#<Directory "/web">
#	AddType text/plain .sh
#	AddIcon /icons/patch.gif .patch
#</Directory>

#<IfModule ssl_module>
#	SSLCertificateFile ${CFG.cfgdir}/ssl.crt/@NODENAME@.@DOMAIN@.crt
#	SSLCertificateKeyFile ${CFG.cfgdir}/ssl.key/@NODENAME@.@DOMAIN@.key
#</IfModule>

# vim: ts=4 filetype=apache
EOF
	copyTempFile "${CONF}" 0444

	typeset TEMPLATE="${CONF}"
	getConf CONF sites/${CFG.fqdn}
	NODENAME=${CFG.fqdn%%.*}
	DOMAIN=${CFG.fqdn#*.}
	gsed -e "s/@NODENAME@/${NODENAME}/g" -e "s/@DOMAIN@/${DOMAIN}/g" \
		${TEMPLATE} > "${CFG.tfile}"
	copyTempFile "${CONF}"

	CFG.config=1
}

Man.addFunc updateCertHasher '' '[+NAME?updateCertHasher - aktuallisiert script zum Anlegen der SSL-Zertifikat-Links]
[+DESCRIPTION?Aktualisiert das script \bssl.crt/hashCerts\b im config Verzeichnis, das für das Aktualisieren/Löschen der Hash-Symlinks auf die jeweiligen SSL-Zertifikate im selben Verzeichnis zuständig ist. Das Script muß jedesmal manuell gestartet werden, wenn sich der Inhalt eines SSL-Zertifikats ändert oder neue hinzugekommen sind.]
[+?Falls die relevanten Verzeichnis noch nicht vorhanden sind, werden diese automatisch erstellt.]
[+SEE ALSO?\bcheckDirs()\b, \bcopyTempFile()\b]
'
function updateCertHasher {
	(( ${CFG.hasher} )) && return
	checkDirs
	typeset FILE="${CFG.cfgdir}/ssl.crt/hashCerts"
	[[ -e ${FILE} ]] && + cp -p "${FILE}" "${FILE}.old"
	cat >${CFG.tfile}<<EOF
#!/bin/ksh93

OPENSSL=\${ whence openssl; }
[[ -z \${OPENSSL} || ! -x \${OPENSSL} ]] && \\
	print -u2 "openssl program not found - exiting." && exit 1

SDIR=\${.sh.file} && SDIR=\${SDIR%/*} && [[ \${SDIR} == \${.sh.file} ]] && SDIR=\${PWD}

Usage() {
	print -u2 '
Usage: %s [-h] [-d dir]

Remove old openssl hash symbolic links to *.crt files and re-create them in
the target directory.

  -h     .. print this help and exit.
  -d dir .. target directory. Default: Directory, which contains this script.
' \${0##*/}
}

while getopts "hd:" option ; do
	case "\${option}" in
		h) Usage ; exit 0 ;;
		d) SDIR="\${OPTARG}" ;;
	esac
done

cd "\${SDIR}"
(( \$? != 0 )) && exit 1

# remove old stuff
for FILE in [0-9a-fA-F]*.[0-9]*; do
	[[ ! -L \${FILE} ]] && continue
	LSI=( \${ ls -l \${FILE} ; } )
	DST=\${LSI[10]}
	[[ -z \${DST} || \${DST##*.} != 'crt' ]] && continue
	rm -f \${FILE}
done

# re-create links
integer N
FORMAT="%-15s ... %s\n"
for FILE in *.crt; do
	[[ ! -e \${FILE} ]] && continue
	grep -q SKIPME \${FILE}
	(( \$? == 0 )) && printf "\${FORMAT}" "\${FILE}" 'Skipped' && continue
	N=0
	while (( N < 256 )); do
		HASH=\${ \${OPENSSL} x509 -noout -hash < \${FILE}; }
		[[ -r \${HASH}.\$N ]] && (( N++ )) && continue
		printf "\${FORMAT}" "\${FILE}" "\${HASH}.\$N"
		ln -s "./\${FILE}" "\${HASH}.\$N"
		break
	done
done
EOF
	copyTempFile "${FILE}" 0755
	CFG.hasher=1
}

function showUsage {
	typeset WHAT="$2"
	getopts -a "$PROG" "${ print ${Man.FUNC[$WHAT]}; }" OPT --man
}

ApacheEnv_t CFG
CFG.init '/data/web'

Man.addFunc MAIN '' '[+NAME?'"${PROG}"' - Basiskonfiguration der default HTTP-Instanz einer zone]
[+DESCRIPTION?Mit dem Script kann in einer globalen oder nicht-globalen Zone die default HTTPd-Instanz konfiguriert werden. Es bezieht sich immer auf die Zone, in der dieses Script gestartet wird.]
[+?Sind die notwendigen Verzeichnisse/ZFS oder Konfig-Dateien noch nicht vorhanden, werden sie automatisch von diesem Script erstellt. Dies erfordert u.U. entsprechende SMF-Authorisierung und erweiterte Rechte zum Schreiben der jeweiligen Dateien bzw. ihres Besitzers/Rechte. Falls der diese Script Ausführende keine entsprechende Rolle (z.B. Primary Administator) besitzt, muß dieses Script als user root ausgeführt werden.]
[h:help?Diese Hilfe ausgegeben und Script beenden.]
[F:functions?Liste aller definierten Funktionen im Script ausgeben (\btypeset +f\b).]
[H:usage]:[function?Hilfe für die angegebene Script-Funktion bzw. Objekttyp anzeigen (soweit verfügbar) und Script beenden. Siehe auch Option \b-F\b.]
[T:trace]:[fname_list?Eine Komma- oder Leerzeichen-separierte Liste von Funktionsnamen, die während ihrer Ausführung getracet werden sollen.]
[d:data]:[dir?Ordner, unter dem der sites Daten-Ordner angeleget werden soll (falls noch nicht vorhanden) inkl. Verzeichnisse für die Web-Sites. Default: '"${CFG.basedir}"']
[z:zfsBase]:[name?ZFS name unter dem das data Verzeichnis angelegt werden soll, falls noch nicht vorhanden. Default: in der globalen zone \a$POOL/$HOST\a ('"${CFG.zfsbase}"'), \bpool1\b sonst (was \a$POOL/$ZNAME/\a\bpool1\b in der globalen zone referenzieren sollte).]
[n:name]:[fqdn?Der volle DNS-Name der website. Default: '"${CFG.fqdn}"']
[s:service?SMF service properties aktualisieren.]
[c:config?Konfig-Dateien erstellen/aktualisieren.]
[u:certs?Das \bssl.crt/hashCerts\b Script aktualisieren.]
[o:overwrite?Wenn angegeben, wird von den relevanten httpd *.conf Dateien eine Sicherungskopie mit einem Timestamp als Suffix erstellt, bevor sie überschrieben werden. Falls nicht angegeben, wird keine httpd *.conf Datei überschrieben: stattdessen wird die neue Konfig in einer entsprechenden Datei mit einem Timestamp als Suffix gespeichert.]
[O:owner]:[name?Der zukünftige Besitzer der Konfig-Dateien und website Verzeichnisse. Default: '"${CFG.owner}"']
[G:group]:[name?Name der Gruppe, die dem Daten-Ordner zugeordnet werden soll. Default: '"${CFG.group}"'] 
[p:port]:[num?Port, der für das HTTP-Protokoll verwendet werden soll. Default: '"${CFG.port}"']
[P:sslport]:[num?Port, der für das HTTPS-Protokoll verwendet werden soll. Default: '"${CFG.sslport}"'
'
integer CMD=0
X="${ print ${Man.FUNC[MAIN]} ; }"
while getopts "${X}" option ; do
	case "${option}" in
		h) showUsage ${PROG} MAIN ; exit 0 ;;
		F) typeset +f ; exit 0 ;;
		H)  if [[ ${OPTARG%_t} != ${OPTARG} ]]; then
				${OPTARG} --man   # self-defined types
			else
				showUsage "${OPTARG}" "${OPTARG}"   # function
			fi
			exit 0
			;;
		T) 
			if [[ ${OPTARG} == 'ALL' ]]; then
				typeset -ft ${ typeset +f ; }
			else
				typeset -ft ${OPTARG//,/ }
			fi
			;;
		d) CFG.setBaseDir "${OPTARG}" ;;
		z) CFG.zfsbase="${OPTARG}" ;;
		n) CFG.fqdn="${OPTARG}" ;;
		o) CFG.overwrite=1 ;;
		x) CMD=ok ;;
		s) (( CMD|=1 )) ;;
		c) (( CMD|=2 )) ;;
		u) (( CMD|=4 )) ;;
		O) CFG.owner="${OPTARG}" ;;
		G) CFG.group="${OPTARG}" ;;
		p) CFG.port=${OPTARG} ;;
		P) CFG.sslport=${OPTARG} ;;
	esac
done
X=$((OPTIND-1))
shift $X

(( ! ${CMD} )) && showUsage ${PROG} MAIN && exit 1
CFG.getDefaults

(( $CMD & 1 )) && updateSvc
(( $CMD & 2 )) && createConf
(( $CMD & 4 )) && updateCertHasher
