#!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

pidfile = '/var/run/plancton.pid'
logdir = '/var/log/plancton'
confdir = '/etc/plancton'

# Parse command-line arguments
try:
  opts, args = getopt(sys.argv[1:], '', [ '--user', 'logdir=', 'pidfile=', 'confdir=' ])
  for o, a in opts:
    if o == '--pidfile':
      pidfile = a
    elif o == '--logdir':
      logdir = a
    elif o == '--confdir':
      confdir = a
    elif o == '--user':
      home = os.path.expanduser('~/.plancton')
      pidfile = '%s/plancton.pid' % home
      logdir = '%s/log' % home
      confdir = '%s/conf' % home
      if not os.path.isdir(daemondir):
        os.mkdir(daemondir, 0700)
      else:
        os.chmod(daemondir, 0700)
    else:
      assert False, 'This should not happen: o=%s a=%s' % (o, a)

except GetoptError as e:
  sys.stderr.write('plancton: %s\n' % e)
  sys.exit(1)

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

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

def help():
  sys.stderr.write('Usage: %s [start|stop|status|nodaemon|help]\n' % os.path.basename(sys.argv[0]))

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()
elif cmd == 'help':
  help()
  r = True
else:
  help()
  r = False

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

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