#!/usr/bin/env python
#

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

from __future__ import absolute_import, print_function

import json
import os
import shutil
import sys

from optparse import OptionParser

try:
    from urllib.request import urlopen
    from urllib.parse import urlencode
except ImportError:
    from urllib2 import urlopen
    from urllib import urlencode

try:
    import gterm
except ImportError:
    import graphterm.bin.gterm as gterm

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("Usage: gcp <source_file_url> <dest_file_url>", file=sys.stderr)
    sys.exit(1)

src_uri, dst_uri = args

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

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

src_file = None
if not src_comps or not src_comps[gterm.JHOST]:
    src_file = src_comps[gterm.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("Unable to write to %s" % dst_file, file=sys.stderr)
        sys.exit(1)
    dst_file = os.path.join(dst_file, src_comps[gterm.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("Unable to read from %s" % src_file, file=sys.stderr)
        sys.exit(1)

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

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

    if resp.code != 200:
        print("Failed to retrieve file: %d\n%s" % (resp.code, resp.read()), file=sys.stderr)
        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)
