#!/usr/bin/env bash

#
# Helper utility for file operations with Apache's configuration files.
#

usage() {
    cat << EOH

Usage: $0 [options]

 Helper utility for working with Apache's configuration files

OPTIONS:
 -t      - Test current configuration of web server.
 -d      - Create directory.
 -w file - Write content from stdin to the specified file. Makes backup
           of target file.

EOH
}

write() {

    filename="$1"

    directory=`dirname "$filename"`
    mkdirectory "$directory"
    if [ "x$?" != "x0" ] ; then
        ERROR=$?
        echo "Can not create directory $directory" >&2
        return $ERROR
    fi

    # Check target file can be replaced
    if [ -f "$filename" ] ; then
        if [ ! -w "$filename" -o ! -r "$filename" ] ; then
            echo "Can not read/write to $filename" >&2
            return 100
        fi
    fi

    # Put new content into temporary file
    tmpfile=`mktemp "$filename".XXXXXX`
    if [ "x$?" != "x0" -o ! -w "$tmpfile" ] ; then
        echo "Can not create temporary file $tmpfile" >&2
        return 101
    fi

    cat > "$tmpfile"
    if [ "x$?" != "x0" ] ; then
        echo "Error writing to $tmpfile" >&2
        rm -f "$tmpfile"
        return 101
    fi

    # Check that new file is not empty
    if [ ! -s "$tmpfile" ] ; then
        echo "No or empty input supplied on utility's standard input stream!" >&2
        rm -f "$tmpfile"
        return 101
    fi

    # Remove existing target file
    if [ -f "$filename" ] ; then
        rm -f "$filename"
        if [ "x$?" != "x0" ] ; then
            echo "Can not remove existing file $filename" >&2
            rm -f "$tmpfile"
            return 100
        fi
    fi

    # Commit changes to target file (disable interactivity in mv)
    mv -f "$tmpfile" "$filename"
    if [ "x$?" != "x0" ] ; then
        ERROR=$?
        rm -f "$tmpfile"
        return $ERROR
    fi

    # Correct owner & permissions
    chmod 640 "$filename"
    chown "root":"www" "$filename"

    return $?
}

mkdirectory() {

    path="$1"

    if [ -d "$path" ] ; then
        return 0
    fi

    if [ -e "$path" ] ; then
        echo "File $path already exists" >&2
        return 100
    fi

    mkdir "$path"
    if [ "x$?" != "x0" ] ; then
        ERROR=$?
        return $ERROR
    fi

    chmod 770 "$path"
    if [ "x$?" != "x0" ] ; then
        ERROR=$?
        return $ERROR
    fi
    chown "wwwrun":"psacln" "$path"
    if [ "x$?" != "x0" ] ; then
        ERROR=$?
        return $ERROR
    fi

    return $?
}

if [ $# -eq 0 ] ; then
    usage
    exit 0
fi

getopts "td:w:" OPTION

ERROR=0
case $OPTION in
    t)
        [ ! -e "/etc/apache2/envvars" ] || source /etc/apache2/envvars
        /usr/sbin/httpd2 -t
        ERROR=$?
        ;;
    d)
        mkdirectory "$OPTARG"
        ERROR=$?
        ;;
    w)
        write "$OPTARG"
        ERROR=$?
        ;;
    *)
        usage
        ERROR=1
        ;;
esac

exit $ERROR
