#!/usr/bin/python

import json, os, sys

home = os.environ['HOME']

if 'TMUX' in os.environ:
    prefix = '\x1bPtmux;\x1b'
    postfix = '\x1b\\'
else:
    prefix = ''
    postfix = ''

def process(paths):
    v = []
    for path in paths:
        #if not os.path.exists(path):
        #    raise RuntimeError("path '%s' does not exist"%path)

        path = os.path.abspath(path)
        # determine name relative to home directory
        if path.startswith(home):
            name = path[len(home)+1:]
        else:
            name = path

        # Is it a file or directory?
        if os.path.isdir(path):
            v.append({'directory':name})
        else:
            v.append({'file':name})

    if len(v) > 0:
        mesg = {'event':'open', 'paths':v}
        print prefix + '\x1b]49;%s\x07'%json.dumps(mesg,separators=(',',':')) + postfix

if len(sys.argv) == 1:
    print "Usage: open [path names] ..."
    print "Opens each file (or directory) in the Sagemath Cloud web-based editor from the shell."
    print "If the named file doesn't exist, you get an error (the file is *not* created)."
else:
    process(sys.argv[1:])
