#!/usr/bin/env python
import sys
import yaml
import socket
import tempfile
import subprocess

def usage():
  print "usage: synergy_invoke YAML_FILE"

def gen_server_synergy_conf(config):
  #temp = tempfile.NamedTemporaryFile()
  temp_file = tempfile.mkstemp()[1]
  temp = file(temp_file,"w")
  server = [c['server'] for c in config if c.has_key('server')][0]
  servername = server['name']
  clients = [c['client'] for c in config if c.has_key('client')]
  temp.write("""section: screens
  %s:
  %s
  end
  """ % (servername,
  "\n".join([c['name'] + ":" for c in clients])))
  
  temp.write("section: links\n")
  temp.write(servername + ":\n")
  for pos in server['positions']:
    temp.write(pos['position'] + "\n")
  for client in clients:
    name = client['name']
    temp.write("%s:\n" % name)
    for position in client['positions']:
      position = position['position']
      temp.write(position + "\n")
  temp.write("end")
  return temp_file

def invoke_synergy(config, hostname):
  servername = [c['server']['name'] for c in config if c.has_key('server')][0]
  clients = [c['client']['name'] for c in config if c.has_key('client')]
  if servername == hostname:
    config_fname = gen_server_synergy_conf(config)
    cmd = "synergys -c " + config_fname
    print cmd
    subprocess.check_call(cmd.split(" "))
  elif hostname in clients:
    cmd = "synergyc " + servername
    print cmd
    subprocess.check_call(cmd.split(" "))

if __name__ == "__main__":
  if len(sys.argv) < 2:
    usage()
    exit(1)
  yaml_file = sys.argv[1]
  config = yaml.load(open(yaml_file).read())
  hostname = socket.gethostname()
  invoke_synergy(config, hostname)

