#!/usr/bin/env python

import os
from optparse import OptionParser
import sys
from time import sleep

from wader.common.consts import (APP_VERSION, DATA_DIR, PID_PATH)
sys.path.insert(0, DATA_DIR)

from twisted.python.release import sh


def stop_core():
    if os.path.exists(PID_PATH):
        sh("kill -9 `cat %s`" % PID_PATH)

parser = OptionParser()
parser.add_option("-v", "--version", action="store_true", dest="show_version",
                  default=False, help="Show version and exit")
parser.add_option("-r", "--restart", action="store_true",
                  dest="should_restart", default=False,
                  help="Restart wader-core")
parser.add_option("-s", "--start", action="store_true", dest="should_start",
                  default=False,
                  help="Start wader-core (only to be called by D-Bus service)")
parser.add_option("-t", "--stop", action="store_true", dest="should_stop",
                  default=False, help="Stop wader-core")

options, args = parser.parse_args()

if not (options.show_version or options.should_restart or
        options.should_start or options.should_stop):
    print(parser.format_help().strip())
    sys.exit(0)

if options.show_version:
    print "%s: version %s" % (os.path.basename(sys.argv[0]), APP_VERSION)
    sys.exit(0)

if options.should_stop:
    stop_core()

if options.should_restart:
    try:
        stop_core()
    except:
        print "Failed to stop core cleanly, may still be running"

    sleep(1)

    sh("dbus-send --system --dest=org.freedesktop.ModemManager "
       "/org/freedesktop/ModemManager "
       "org.freedesktop.ModemManager.EnumerateDevices")

elif options.should_start:
    from twisted.scripts.twistd import run
    from sys import argv
    argv[1:] = [
        '--python=%s' % os.path.join(DATA_DIR, 'core-tap.py'),
        '--pidfile=%s' % PID_PATH,
        '--reactor=glib2'
    ]
    run()
