#!/usr/bin/env python
# -*- coding: utf-8 -*-
## @file plancton
#  Main executable for the plancton daemon.
#
#  Prepares working directories and the environment, then invokes methods from the Plancton class.
#  This script can be used in a way that resembles the `/etc/init.d` scripts.

import sys, os.path
from getopt import getopt, GetoptError
from plancton import Plancton

daemondir = None
pidfile = None
logdir =  None
confdir =  None

# Parse command-line arguments
try:
    opts, args = getopt(sys.argv[1:], '', [ 'logdir=', 'pidfile=', 'daemondir=', 'confdir=' ])
    for o, a in opts:
        if o == '--daemondir':
            daemondir = a
        elif o == '--pidfile':
            pidfile = a
        elif o == '--logdir':
            logdir = a
        elif o == '--confdir':
            confdir = a
        else:
            assert False, 'This should not happen: o=%s a=%s' % (o, a)

except GetoptError as e:
    print 'plancton: %s' % e
    sys.exit(1)

if daemondir is None:
    force_daemondir = False
    daemondir = os.path.expanduser('~/.plancton')
else:
    force_daemondir = True

if not force_daemondir and daemondir.startswith('/var/lib/plancton'):
    # Detected a system-wide installation
    daemondir = None
    pidfile_default = '/var/run/plancton.pid'
    logdir_default = '/var/log/plancton'
    confdir_default = '/etc/plancton'
else:
    pidfile_default = '%s/plancton.pid' % daemondir
    logdir_default = '%s/log' % daemondir
    confdir_default = '%s/conf' % daemondir

    if not os.path.isdir(daemondir):
        os.mkdir(daemondir, 0700)
    else:
        os.chmod(daemondir, 0700)

if pidfile is None:
    pidfile = pidfile_default
if logdir is None:
    logdir = logdir_default
if confdir is None:
    confdir = confdir_default

try:
    cmd = args[0]
except IndexError:
    cmd = None

daemon_instance = Plancton('plancton', pidfile=pidfile, logdir=logdir, confdir=confdir)

r = None
if cmd == 'start':
    r = daemon_instance.start()
elif cmd == 'stop':
    r = daemon_instance.stop()
elif cmd == 'status':
    r = daemon_instance.status()
elif cmd == 'nodaemon':
    r = daemon_instance.run()
else:
    sys.stderr.write( 'Usage: %s [start|stop|status|nodaemon]\n' % os.path.basename(sys.argv[0]) )
    r = False

if isinstance(r, bool):
    if r == True:
        sys.exit(0)
    else:
        sys.exit(1)
elif isinstance(r, int):
    sys.exit(r)

# Invalid return code?
assert False, 'Invalid return code: %s' % r
