#!/usr/bin/env python
import sys
import os
import json
import random 

env = {}
env.update(os.environ)
env.update(json.load(open('/home/dotcloud/environment.json')))

# Make all DOTCLOUD_$SERVICENAME_FOO variables available as FOO as well
service_name = env['DOTCLOUD_SERVICE_NAME']
prefix = 'DOTCLOUD_{0}_'.format(service_name.upper())
extra_env = {}
for k in env:
    if k.startswith(prefix):
        extra_env[k[len(prefix):]] = env[k]
env.update(extra_env)

service_id = env['DOTCLOUD_SERVICE_ID']

# for backend pagekite connection
tcp_port = str(env['PORT_TCP'])
# for web requests
www_port = str(env['PORT_WWW'])
# tcp port that accepts external connections
external_port = str(env['TCP_PORT_'+service_id])

host = str(env['HTTP_HOST_'+service_id])
secret = env['PAGEKITE_SECRET'] if 'PAGEKITE_SECRET' in env else hex(random.getrandbits(64))[2:-1]

conn_cmd = open('/home/dotcloud/connect_instructions','w');
conn_cmd.write("\n# Connect to Pagekite using the following command:\n#\n")
conn_cmd.write("# pagekite.py --frontend={host}:{port} --service_on=http:{host}:localhost:PORT:{secret}\n#\n"
               .format(host=host, port=external_port, secret=secret));
conn_cmd.write("# Replace PORT with the port your local service is running on.\n\n");
conn_cmd.close();

args = ['python','./pagekite.py','--isfrontend','--ports='+www_port+','+tcp_port, '--domain=*:'+host+':'+secret]
#print args
os.execvp('python', args)
