#!/usr/bin/env python
#
# cuckooctl - start/stop/query the CuckooChimeAgent background process
# part of Cuckoo, http://toastycode.com/cuckoo/
# (c) 2007 toastycode
# author: Daniel Sandler <dsandler@toastycode.com>

__version__ = '0.1'

import sys

from AppKit import *

CUCKOO_BUNDLE_ID = "com.toastycode.Cuckoo"

PREF_ENABLE = "enable"

CUCKOO_PREFS_NOTIFICATION = "CuckooPrefsChanged"
CUCKOO_TEST_NOTIFICATION = "CuckooTestChime"

CUCKOO_CHIME_AGENT = "CuckooChimeAgent"

args = sys.argv[:]

if len(args) == 1:
    args.append("-h")

def run_as(t):
    return NSAppleScript.alloc().initWithSource_(t).executeAndReturnError_(None)

def notify(notification=CUCKOO_PREFS_NOTIFICATION):
    NSDistributedNotificationCenter.defaultCenter().postNotificationName_object_(
        notification, None)

def get_domain():
    sud = NSUserDefaults.standardUserDefaults()
    sud.synchronize()
    return sud.persistentDomainForName_(CUCKOO_BUNDLE_ID)

def set_domain(d):
    sud = NSUserDefaults.standardUserDefaults()
    sud.removePersistentDomainForName_(CUCKOO_BUNDLE_ID)
    sud.setPersistentDomain_forName_(d, CUCKOO_BUNDLE_ID)
    sud.synchronize()

def set_enabled(e):
    d = NSMutableDictionary.alloc().init()
    d.addEntriesFromDictionary_(get_domain())
    d.setObject_forKey_(NSNumber.numberWithBool_(e), PREF_ENABLE)
    set_domain(d)

def get_enabled():
    return bool(get_domain().objectForKey_(PREF_ENABLE).booleanValue())

if args[1] == "start":
    set_enabled(True)
    NSWorkspace.sharedWorkspace().launchApplication_(CUCKOO_CHIME_AGENT)
elif args[1] == "stop":
    set_enabled(False)
    notify()
elif args[1] == "restart":
    NSWorkspace.sharedWorkspace().launchApplication_(CUCKOO_CHIME_AGENT)
elif args[1] == "test":
    notify(CUCKOO_TEST_NOTIFICATION)
elif args[1] == "status":
    result = run_as('''tell application "System Events" to get ("%s" is in name of every application process)''' % CUCKOO_CHIME_AGENT)
    print ["stopped","running"][int(result[0].booleanValue())]
else:
    print "usage: cuckooctl {start|stop|restart|status|test}"
    sys.exit(1)
