#!/bin/sh

if [ ! -d "/var/www/werc/sites/$HOSTNAME" ]; then
    echo "Index directory for hostname $HOSTNAME does not exist. Creating..."
    cp -r /var/www/werc/sites/werc.cat-v.org "/var/www/werc/sites/$HOSTNAME"
    echo "# Hello World!" > "/var/www/werc/sites/$HOSTNAME/index.md"
fi

CONF_FILE="/etc/lighttpd/conf.d/$HOSTNAME.conf"
if [ ! -f "$CONF_FILE" ]; then
    echo "Creating new configuration file: $CONF_FILE"
    cat << EOF > "$CONF_FILE"
\$HTTP["host"] =~ "^$(echo "$HOSTNAME" | sed 's/\./\\./g')$" {
    index-file.names = ( )
    server.error-handler-404 = "/werc.rc"
    alias.url       += ( "/werc.rc" => "/var/www/werc/bin/werc.rc" )
    cgi.assign += ( ".rc" => "" )
}
EOF
fi

echo "Running lighttpd"
chmod a+w /dev/pts/0
exec lighttpd -D -f /etc/lighttpd/lighttpd.conf
