#!/usr/bin/env python
#

"""
gcp: graphterm-aware copy
"""

import json
import os
import shutil
import sys
import urllib
import urllib2

from optparse import OptionParser

import gtermapi

BLOCK_SIZE = 8192

usage = "usage: %prog gcp <source_file_url> <dest_file_url>"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=False,
                  help="Verbose")

(options, args) = parser.parse_args()
location = " ".join(args)

if len(args) != 2:
    print >> sys.stderr, "Usage: gcp <source_file_url> <dest_file_url>"
    sys.exit(1)

src_uri, dst_uri = args

src_comps = gtermapi.split_file_url(src_uri, check_host_secret=gtermapi.Shared_secret)
dst_comps = gtermapi.split_file_url(dst_uri, check_host_secret=gtermapi.Shared_secret)

if dst_comps:
    if dst_comps[gtermapi.JHOST]:
        print >> sys.stderr, "Remote copy destination not implemented"
        sys.exit(1)
    dst_file = dst_comps[gtermapi.JFILEPATH]
else:
    dst_file = dst_uri
    

src_file = None
if not src_comps or not src_comps[gtermapi.JHOST]:
    src_file = src_comps[gtermapi.JFILEPATH] if src_comps else src_uri

if os.path.exists(dst_file):
    if not os.path.isdir(dst_file) or not os.access(dst_file, os.W_OK):
        print >> sys.stderr, "Unable to write to %s" % dst_file
        sys.exit(1)
    dst_file = os.path.join(dst_file, src_comps[gtermapi.JFILENAME] if src_comps else os.path.basename(src_file))

if src_file:
    if not os.path.isfile(src_file) or not os.access(src_file, os.R_OK):
        print >> sys.stderr, "Unable to read from %s" % src_file
        sys.exit(1)

    if options.verbose:
        print >> sys.stderr, "Copying %s -> %s" % (src_file, dst_file)
    shutil.copyfile(src_file, dst_file)

else:
    req_url = gtermapi.URL+gtermapi.FILE_PREFIX+src_comps[gtermapi.JHOST]+src_comps[gtermapi.JFILEPATH]+src_comps[gtermapi.JQUERY]+"&"+urllib.urlencode({"host": gtermapi.Host, "shared_secret": gtermapi.Shared_secret})
    if options.verbose:
        print >> sys.stderr, "Copying %s -> %s" % (req_url, dst_file)
    try:
        resp = urllib2.urlopen(req_url)
    except Exception, excp:
        print >> sys.stderr, "Failed to retrieve file: %s" % excp
        sys.exit(1)

    if resp.code != 200:
        print >> sys.stderr, "Failed to retrieve file: %d\n%s" % (resp.code, resp.read())
        sys.exit(1)

    with open(dst_file, "wb") as fp:
        content_length = int(resp.headers["content-length"])
        count = 0
        while True:
            chunk = resp.read(BLOCK_SIZE)
            if not chunk:
                break
            fp.write(chunk)
            # Display progress information
            count += len(chunk)
