#!/usr/bin/python
#
# Take posted keyring data and store it somewhere.  Hand it back on demand.
#
#################
import cgi

STORAGE = '/path/to/a/file/keyring.json'
# Datestamped backups stored here
BACKUP = '/path/to/a/directory'

def show_form(msg=''):
    print """Content-type: text/html

<html><head>
<title>Enter data</title>
</head><body>"""
    if msg:
        print "<h1>", msg, "</h1>\n"
    print """<h2>Enter data</h2>
<form action="/cgi-bin/keyring.py" method="POST">
  Data: <textarea name="data"></textarea>
  <input type="submit" value="go" />
</form>
</body></html>"""

def get_data():
    try:
        storage = open(STORAGE, 'r')
    except:
        print "Content-type: text/plain\n\nERROR reading", STORAGE
        return
    data = storage.read()
    storage.close()
    print "Content-type: text/plain\n\n", data


def post_data(data):
    try:
        storage = open(STORAGE, 'w')
        storage.write(data)
        storage.close()
    except:
        print "Content-type: text/plain\n\nERROR writing", STORAGE
        return
    backup_fname = os.path.join(BACKUP,
        datetime.date.isoformat(datetime.date.today()) + '.json')
    try:
        backup = open(backup_fname, 'w')
        backup.write(data)
        backup.close()
    except:
        print "Content-type: text/plain\n\nERROR writing", backup_fname
        return
    print "Content-type: text/plain\n\nOK"


if __name__ == '__main__':
    form = cgi.FieldStorage()
    if not form:
        get_data()
    elif form.has_key('form'):
        show_form()
    else:
        post_data(form.getfirst('data'))
