# sftp.py - dput method for sftp transport
#
# @author Cody A.W. Somerville <cody.somerville@canonical.com>
# @company Canonical Ltd.
# @date 07 November 2008
#

import os, sys, dputhelper

def upload(fqdn, login, incoming, files, debug, compress, progress=0):
    try:
        import bzrlib.transport
    except Exception, e:
        print "E: bzrlib must be installed to use sftp transport."
        sys.exit(1)

    if not login or login == '*':
        login = os.getenv("USER")

    if not incoming.endswith("/"):
        incoming = "%s/" % incoming

    try:
        t = bzrlib.transport.get_transport("sftp://%s@%s/%s" % (login, fqdn, incoming))
    except Exception, e:
        print "%s\nE: Error connecting to remote host." % e
        sys.exit(1)

    for f in files:
        baseFilename = f.split("/")[len(f.split("/"))-1]
        sys.stdout.write("  %s: " % baseFilename)
        sys.stdout.flush()
        try:
            fileobj = open(f, 'rb')

            if progress:
                try:
                    size = os.stat(f).st_size
                except:
                    size = -1
                    if debug:
                        print "D: Determining size of file '%s' failed" % f

                fileobj = dputhelper.FileWithProgress(fileobj, ptype=progress,
                                                      progressf=sys.stdout,
                                                      size=size)

            t.put_file(baseFilename, fileobj)
            fileobj.close()
        except Exception, e:
            print "\n%s\nE: Error uploading file." % e
            sys.exit(1)
        print "done."
