#!/usr/bin/env python
#

"""
gupload: graphterm-aware upload

To upload file:
   gupload directory/filename

To pipe uploaded data:
   gupload | cat > outfile

To switch stdout and stderr:
   gupload 3>&1 1>&2 2>&3-
"""

from __future__ import absolute_import, print_function

import base64
import json
import os
import sys
import tty
import termios

from optparse import OptionParser

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

CHUNK_BYTES = 4096

Work_dir = os.getenv("PWD", "") or os.getcwd()

usage = "usage: %prog [-f] [<filepath/directory>]"
parser = OptionParser(usage=usage)
parser.add_option("-w", "--write",
                  action="store_true", dest="write", default=False,
                  help="Overwrite existing file")
parser.add_option("-o", "--stdout",
                  action="store_true", dest="stdout", default=False,
                  help="Use STDOUT for pagelet output")
parser.add_option("-l", "--loop",
                  action="store_true", dest="loop", default=False,
                  help="Loop (multiple) uploads")
parser.add_option("-q", "--quiet",
                  action="store_true", dest="quiet", default=False,
                  help="Quiet")
parser.add_option("", "--verbose",
                  action="store_true", dest="verbose", default=False,
                  help="Verbose")

(options, args) = parser.parse_args()

if len(args) > 1:
    print("To many arguments", file=sys.stderr)
    sys.exit(1)

assert sys.stdin.isatty()

to_dir = False
if args:
    expname = os.path.expanduser(args[0])
    filepath = os.path.normcase(os.path.normpath(os.path.join(Work_dir, expname)))
elif sys.stdout.isatty():
    filepath = "."
else:
    filepath = ""

if filepath:
    if os.path.exists(filepath):
        if os.path.isdir(filepath):
            to_dir = True
        elif not options.write:
            print("Specify -w option to overwrite file %s" % filepath, file=sys.stderr)
            sys.exit(1)
    else:
        head, tail = os.path.split(filepath)
        if head:
            if os.path.exists(head):
                if not os.path.isdir(head):
                    print("Cannot overwrite file %s" % head, file=sys.stderr)
                    sys.exit(1)
            else:
                print("Please create directory %s" % head, file=sys.stderr)
                sys.exit(1)

if options.loop and not to_dir:
    sys.exit("Error: loop option inconsistent with non-directory destination")

while True:
    if not options.quiet and not options.stdout:
        print("Uploading file...", file=sys.stderr)

    params = {"display": "block", "current_directory": Work_dir}
    html_headers = {"x_gterm_response": "upload_file",
                    "x_gterm_parameters": params
                    }
    gterm.wrap_write("", headers=html_headers, stderr=not options.stdout)

    try:
        errmsg, headers, content = gterm.receive_data(stderr=not options.stdout, binary=True, verbose=options.verbose)
        if errmsg or "x_gterm_filepath" not in headers:
            gterm.write_blank(stderr=not options.stdout)
            sys.exit(errmsg or 1)
        filename = headers["x_gterm_filepath"]
    except KeyboardInterrupt:
        sys.exit(1)

    gterm.write_blank(stderr=not options.stdout)

    if filepath:
        Stdout_data = None
        if to_dir:
            tempath = os.path.join(filepath, filename)
        else:
            tempath = filepath
        with open(tempath, "wb") as f:
            f.write(content)
        if not options.quiet:
            print("Uploaded file "+tempath, file=sys.stderr)

        if not options.loop:
            break
    else:
        Stdout_data = content
        break

if Stdout_data is not None:
    if options.stdout:
        os.write(sys.stderr.fileno(), content)
    else:
        os.write(sys.stdout.fileno(), content)
