#!/bin/sh

set -e

if [ "$1" != "configure" ]; then
    exit 0
fi

# Touch and set permisions on default log files on installation
if [ -z "$2" ]; then
    if [ -d /var/log/nginx ]; then
        if [ ! -e /var/log/nginx/access.log ]; then
            touch /var/log/nginx/access.log
            chmod 640 /var/log/nginx/access.log
            chown nginx:adm /var/log/nginx/access.log
        fi

        if [ ! -e /var/log/nginx/error.log ]; then
            touch /var/log/nginx/error.log
            chmod 640 /var/log/nginx/error.log
            chown nginx:adm /var/log/nginx/error.log
        fi
    fi
fi

if [ -x "/etc/init.d/nginx" ]; then
    if [ -f "/var/run/nginx.pid" ] && kill -0 `cat /var/run/nginx.pid` >/dev/null; then
        /etc/init.d/nginx upgrade || true 
    else
        update-rc.d nginx defaults >/dev/null
        if [ -x "`which invoke-rc.d 2>/dev/null`" ]; then
            invoke-rc.d nginx start || true
        else
            /etc/init.d/nginx start || true
        fi
    fi
fi
