#!/bin/bash

. /etc/apache2/envvars

if [ "$SERVER_NAME" ]; then
    FILE=/etc/apache2/apache2.conf
    if grep -E "^ServerName\s+.*\$" "$FILE" > /dev/null 2>&1; then
        echo "Updated IP."
        sed -ri "s/^(ServerName)(\s+[^ ]*)\s*$/\1 $SERVER_NAME/g" "$FILE" 
    else
        #echo "Added IP."
        echo "ServerName $SERVER_NAME" >> "$FILE"
    fi
fi

## Using exec replaces the current bash process with the given one.
## this is necessary if we want that apache2 receives signals correctly.
exec apache2-foreground "$@"