#!/bin/sh
# -*- indent-tabs-mode: nil; sh-indentation: 4 -*-
#
# Copyright(C) 2012-2013 Brazil
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

prefix=/home/myokoym/work/groonga/groonga.clean/packages/windows/dist-x64

SERVICE_NAME=groonga-httpd
GROONGA_HTTPD=${SERVICE_NAME}
PID_FILE=${prefix}/var/run/groonga/${GROONGA_HTTPD}.pid
TIMEOUT=3

# Source configuration.
if [ -f /etc/default/${SERVICE_NAME} ]; then
    . /etc/default/${SERVICE_NAME}
elif [ -f /etc/sysconfig/${SERVICE_NAME} ]; then
    . /etc/sysconfig/${SERVICE_NAME}
fi

OLD_PID_FILE=${PID_FILE}.oldbin

wait_until () {
    for n in $(seq ${TIMEOUT}); do
        if "$@"; then
            return 0
        fi
        sleep 1
    done
    return 1
}

wait_while () {
    for n in $(seq ${TIMEOUT}); do
        if ! "$@"; then
            return 0
        fi
        sleep 1
    done
    return 1
}

start_master () {
    local pid=$1
    kill -USR2 ${pid}
}

switch_worker () {
    local pid=$1
    kill -WINCH ${pid}
}

stop_master () {
    local pid=$1
    kill -QUIT ${pid}
}

if [ ! -f "${PID_FILE}" ]; then
    echo "PID file isn't found. groonga-httpd may not be running: <${PID_FILE}>"
    exit 1
fi

OLD_PID=$(cat ${PID_FILE})
start_master ${OLD_PID}

if ! wait_until [ -f ${OLD_PID_FILE} ]; then
    echo "Failed to create old PID file: <${PID_FILE}>"
    exit 1
fi

if ! wait_until [ -f ${PID_FILE} ]; then
    echo "Failed to start new groonga-httpd master."
    exit 1
fi

NEW_PID=$(cat ${PID_FILE})

OLD_WORKER_PROCESSES=$(pgrep -P ${OLD_PID} | grep -v ${NEW_PID})
switch_worker ${OLD_PID}
for pid in ${OLD_WORKER_PROCESSES}; do
    wait_while ps --pid=${pid} > /dev/null
done
OLD_WORKER_PROCESSES=$(pgrep -P ${OLD_PID} | grep -v ${NEW_PID})
if [ -n "${OLD_WORKER_PROCESSES}" ]; then
    echo "Failed to stop old groonga-httpd worker process."
    stop_master ${NEW_PID}
    echo "Rollback to old groonga-httpd master."
    exit 2
fi

stop_master ${OLD_PID}
exit $?
