#!/usr/bin/env python

import struct
import sys
import json
import mmap

# Helper function that sends a message to the webapp.
def send_message(message):
   # Write message size.
  sys.stdout.write(struct.pack('I', len(message)))
  # Write the message itself.
  sys.stdout.write(message)
  sys.stdout.flush()

def Main():
  while 1:
    # Read the message length (first 4 bytes).
    text_length_bytes = sys.stdin.read(4)

    if len(text_length_bytes) == 0:
      sys.exit(0)

    # Unpack message length as 4 byte integer.
    text_length = struct.unpack('i', text_length_bytes)[0]
    # Read the text (JSON object) of the message.
    text = sys.stdin.read(text_length).decode('utf-8')
    decoded = json.loads(text)
    if "url" in decoded:
        file = open('/dev/shm/timecamp.shared', 'w+')
        file.write(decoded['url'])
        file.close()
        send_message('{"got": "%s"}' % decoded['url'] )



if __name__ == '__main__':
  try:
    Main()
  except:
    print "whoops"
