#!/usr/bin/env python
##
##  trclient.py
##
##  usage: 
##    trclient.py ls lwn
##    trclient.py get lwn.xxxxxxxxxxxxxxxxxxxxxx
##    trclient.py [-e username] put lwn.xxxxxxxxxxxxxxxxxxxxxx
##    trclient.py [-p] getall lwn
##

import sys, os, re, urllib


##  traiss_ls
##
PAT_MODTIME = re.compile(r'<span class="s[0-9]">([^<]*)<')
PAT_TITLE = re.compile(r'<a href="/([^"]+)">([^<]*)<')
PAT_EDITOR = re.compile(r'<em>([^<]*)<')
def traiss_ls(rep, out=sys.stdout):
  fp = urllib.urlopen('http://traiss.tabesugi.net:8080/%s/' % rep)
  stat = 0
  ents = []
  for line in fp:
    if line.startswith('<tr valign=top><td><small>'):
      m = PAT_MODTIME.search(line)
      modtime = m.group(1)
      published = ('>*<' in line)
      stat = 1
    if stat == 1 and line.startswith('<a href="'):
      m = PAT_TITLE.search(line)
      (id, title) = (m.group(1).replace('/','.'), m.group(2).strip())
      stat = 2
    if stat == 2 and line.startswith('<em'):
      m = PAT_EDITOR.search(line)
      editor = m.group(1)
      if editor: editor = '(%s)' % editor
      ents.append((id, modtime, published, title, editor))
      stat = 0
  fp.close()
  #
  if out:
    for (id,modtime,published,title,editor) in ents:
      p = ' '
      if published: p='*'
      out.write('%s %s %s %s %s\n' % (id, modtime, p, title, editor))
  return ents

  
##  traiss_get
##
def traiss_get(rep, id, out=sys.stdout):
  fp = urllib.urlopen('http://traiss.tabesugi.net:8080/%s/%s' % (rep, id))
  stat = 0
  title = []
  desc = []
  published = False
  for line in fp:
    if line.startswith('<textarea accesskey=t name=title'):
      stat = 1
    elif line.startswith('<textarea accesskey=d name=description'):
      stat = 2
    elif line.startswith('</textarea>'):
      stat = 0
    elif line.startswith('<label for=publish>'):
      if ' id=publish checked>' in line:
        published = True
    elif stat == 1:
      title.append(line)
    elif stat == 2:
      desc.append(line)
  fp.close()
  #
  for line in title:
    out.write('# TITLE: '+line)
  out.write('\n')
  for line in desc:
    out.write('# '+line)
  out.write('\n')
  if published:
    out.write('!PUBLISHED\n')
  else:
    out.write('# PUBLISHED\n')
  out.write('\n')
  for line in title:
    out.write('TITLE: '+line)
  out.write('\n')
  for line in desc:
    out.write(line)
  out.write('\n')
  return


##  traiss_put
##
PAT_RESULT = re.compile(r'^<p><span class=[ce]>([^<]+)</span>')
def traiss_put(rep, id, editor, fp=sys.stdin):
  title = ''
  desc = ''
  published = ''
  for line in fp:
    line = line.strip()
    if not line or line.startswith('#'): continue
    if line.startswith('!PUBLISHED'):
      published = 'on'
    elif line.startswith('TITLE:'):
      title += line[6:].strip()+'\n'
    else:
      desc += line+'\n'
  data = urllib.urlencode({'publish':published,
                           'editor':editor,
                           'title':title.strip(),
                           'description':desc.strip(),
                           'cmd':'save'})
  #
  fp = urllib.urlopen('http://traiss.tabesugi.net:8080/%s/%s' % (rep, id), data)
  for line in fp:
    m = PAT_RESULT.match(line)
    if m:
      print m.group(1)
  fp.close()
  return


# main
def main(args):
  import getopt
  def usage():
    print 'usage: trclient.py [-p] [-e name] {ls|get|getall|put} rep[.id] [filename ...]'
    sys.exit(2)
  if not args: usage()
  onlynonpub = False
  editor = os.environ.get('USER', '')
  try:
    (opts, args) = getopt.getopt(sys.argv[1:], "pe:")
  except getopt.GetoptError:
    usage()
  for (k, v) in opts:
    if k == "-p": onlynonpub = True
    elif k == "-e": editor = v

  #
  cmd = args[0]
  args = args[1:]
  if cmd == 'ls':
    if not args: usage()
    traiss_ls(args[1])

  elif cmd == 'get':
    if not args: usage()
    for x in args:
      (rep,id) = x.split('.')
      out = file('%s.%s' % (rep,id), 'w')
      traiss_get(rep, id, out=out)
      out.close()

  elif cmd == 'getall':
    if not args: usage()
    rep = args[0]
    ents = traiss_ls(rep, out=None)
    for (id,modtime,published,title,editor) in ents:
      if onlynonpub and published: continue
      print id, title
      (rep,id) = id.split('.')
      out = file('%s.%s' % (rep,id), 'w')
      traiss_get(rep, id, out=out)
      out.close()

  elif cmd == 'put':
    if not args: usage()
    for x in args:
      print x
      (rep,id) = x.split('.')
      fp = file('%s.%s' % (rep,id))
      traiss_put(rep, id, editor, fp)
      fp.close()

  else:
    usage()
  return

if __name__ == '__main__': main(sys.argv[1:])
