#! /usr/bin/env python
# -----------------------------------------------------------------------------
#    HeartBeat - Yet Another HeartBeat Server
#    Copyright (C) 2011 Some Hackers In Town
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program 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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# -----------------------------------------------------------------------------

import sys
from optparse import OptionParser

from hbeat.daemon import HeartBeatDaemon


parser = OptionParser()
parser.set_defaults(
    port='8998',
    host='127.0.0.1',
    debug=False,
    conf="/etc/heartbeat/heartbeat.conf",
    piddir="/var/run/",
    db = "/etc/heartbeat/hosts.db",
    action=None,
)

parser.add_option('-k', dest='action',
                  help="Do ACTION on debbox. ACTION like {start|stop|status}")
parser.add_option('-f', dest='foreground',
                  action="store_true",
                  help="Run HeartBeat on foreground.")
parser.add_option('-c', dest='conf',
                  help="Use CONF config file. default is" + \
                  "/etc/heartbeat/heartbeat.conf")
parser.add_option('--db', dest='db',
                  help="Use DB database file. default is" + \
                  "/etc/heartbeat/hosts.db")
parser.add_option('--port', dest='port',
                  help="Run HearBeat server on PORT.")
parser.add_option('--host', dest='host',
                  help="Run HeartBeat server on HOST.")
parser.add_option('--debug', dest='debug', action="store_true",
                  help="Activate debug mode.")
parser.add_option('--piddir', dest='piddir',
                  help="Stotr pid files in PIDDIR folder")

options, args = parser.parse_args()
valid_action = False

try:
    daemon = HeartBeatDaemon(options)
except HeartBeatDaemon.CantFindConfigFile:
    print "Error: Can't find '%s' configuration file." % options.conf
    sys.exit(1)

if options.foreground:
    try:
        daemon.start()
    except KeyboardInterrupt:
        daemon.stop()

elif options.action == "start":
        daemon.start()

elif options.action == "stop":
    daemon.stop()

elif options.action == "status":
    daemon.status()

elif valid_action:
    sys.exit(0)

else:
    if options.action:
        print "Error: what is '%s'" % options.action
    else:
        print "Error: Did you forget to pass -k to deamon?"
    sys.exit(1)
