#!/usr/bin/env python

import base64
import os
import hashlib
import json
import dockercloud
import sys

listen_port='55555'
shared_folders=[]
known_hosts=[]
container_name='Default'
service = dockercloud.Service.fetch(os.getenv("DOCKERCLOUD_SERVICE_API_URI").split('/')[6])
for container in service.containers:
	cont = dockercloud.Container.fetch(container.split('/')[6])
        for env in cont.container_envvars:
		if (env['key'] == 'DOCKERCLOUD_IP_ADDRESS'):
			known_hosts.append(env['value'].split('/')[0]+':'+listen_port)
if (len(sys.argv) > 1):
    for v in sys.argv[1:]:
        secret="A"+base64.b32encode(hashlib.sha224(v).hexdigest())[:32]
        folder={'secret':secret,
                'dir':v,
                'use_relay_server':False,
                'use_tracker':False,
                'use_dht':False,
                'search_lan':True,
                'use_sync_trash':False,
                'known_hosts': known_hosts}
        shared_folders.append(folder)
else:
    cont = dockercloud.Container.fetch(os.getenv("DOCKERCLOUD_CONTAINER_API_URI").split('/')[6])
    for v in cont.bindings:
        secret="A"+base64.b32encode(hashlib.sha224(os.getenv("DOCKERCLOUD_SERVICE_API_URI")+v['container_path']).hexdigest())[:32]
        folder={'secret':secret,
                'dir':v['container_path'],
                'use_relay_server':False,
                'use_tracker':True,
                'use_dht':True,
                'search_lan':True,
                'use_sync_trash':False,
                'known_hosts': known_hosts}
        shared_folders.append(folder)
if(len(cont.name) > 1):
	container_name=cont.name
init = {'device_name': container_name,
        'listening_port': int(listen_port),
        'storage_path':'/btsync/.sync',
        'check_for_updates':False,
        'use_upnp':False,
        'download_limit':0,
        'upload_limit':0,
        'shared_folders':shared_folders}

with open('/btsync/btsync.conf', 'w') as configfile:
    json.dump(init,configfile, sort_keys=True,indent=4, separators=(',', ': '))

os.system('btsync --config /btsync/btsync.conf --nodaemon')
