#!/usr/bin/python

import os, sys, re, time

  # Pen button to switch
wacBtn = 'Button2'

  # X buttons to choose from
xBtns = ['2', '3']

  # wacom devices to be switched
devices = ['stylus', 'eraser']





def main():
  
  
  if len(sys.argv) < 2:     # No button specified, just go to the next one in the preferred list
    cb = getCurrentButton()
    if cb in xBtns:
      cInd = (xBtns.index(cb)+1) % len(xBtns)
      next = xBtns[cInd]
    else:
      next = xBtns[0]
  else:
    next = sys.argv[1]
    if not next in xBtns:
      sys.stderr.write("Button %s not allowed.\n" % next)
      sys.exit(-1)
  print "Setting %s to %s" % (wacBtn, next)
  setButton(next)



def runCmd(cmd):
  f = os.popen(cmd)
  l = f.readlines()
  f.close()
  return l

def getCurrentButton():
  setEnv()
  return runCmd("xsetwacom get %s %s" % (devices[0], wacBtn))[0].strip()

def setButton(b):
  setEnv()
  for d in devices:
    os.system("xsetwacom set %s %s %s" % (d, wacBtn, b))
      ## workaround for xsetwacom bug
    os.system("xsetwacom set %s Button1 1" % d)
  for i in range(0, int(b)):
    setLed(0, "off")
    time.sleep(0.1)
    setLed(0, "on")
    time.sleep(0.1)

def setEnv():
  if os.system('pidof kdm') == 0:
    kdmsts = '/var/lib/kdm/kdmsts'
    if os.access(kdmsts, os.R_OK):
      kdmdata = open(kdmsts).readlines()
      userline = filter(lambda s: re.match(r':0=', s), kdmdata)[0]
      user = re.sub(r':0=', '', userline).strip()
      os.environ['DISPLAY'] = ':0.0'
      os.environ['XAUTHORITY'] = '/home/%s/.Xauthority' % user
  elif os.system('pidof gdm') == 0:
    os.environ['DISPLAY'] = ':0.0'
    os.environ['XAUTHORITY'] = '/var/lib/gdm/:0.Xauth'
  
def setLed(n, mode):
  fd = open('/proc/acpi/ibm/led', 'w')
  fd.write("%d  %s" % (n, mode))
  fd.close()
  
main()
