#!/usr/bin/env python3
import sys
import tempfile
import filecmp

import easywebdav
host="localhost"
port=8008


def config():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--port", "-P",
        type=int, default=port,
        help="port the WebDAV-server listens on")
    parser.add_argument(
        "--user", "-u",
        type=str, default=None,
        help="user to authenticate as (if any)")
    parser.add_argument(
        "--password", "-p",
        type=str, default=None,
        help="password to authenticate with (if any)")
    parser.add_argument(
        "file",
        nargs='?', default=__file__,
        help="file to up/download")

    return parser.parse_args()


def runtest(port, localfile, user=None, password=None):
    c = easywebdav.connect(host, port, username=user, password=password)
    print("easywebdav: connect to '%s:%s' as '%s'" % (host, port, user))
    dirnum=0
    dirname="tmp"
    while c.exists(dirname):
       dirnum += 1
       dirname = "tmp.%s" % dirnum
    print("easywebdav: exists '%s'" % (dirname,))
    c.mkdir(dirname)
    print("easywebdav: mkdir '%s'" % (dirname,))
    filename = "file"
    tmpfile = tempfile.NamedTemporaryFile()

    # create a directory, upload <localfile> to it, download it
    c.upload(localfile, dirname + "/" + filename)
    print("easywebdav: upload '%s' to '%s'" % (localfile, dirname + "/" + filename))
    c.cd(dirname)
    print("easywebdav: cd '%s'" % (dirname))
    c.download(filename, tmpfile)
    print("easywebdav: download '%s' to '%s'" % (filename, tmpfile.name,))
    # and remove all traces on the webserver
    c.delete(filename)
    print("easywebdav: delete '%s'" % (filename,))
    c.cd("..")
    print("easywebdav: cd ..")
    c.rmdir(dirname)
    print("easywebdav: rmdir '%s'" % (dirname,))

    # then compare the two files
    tmpfile.flush()
    x = filecmp.cmp(localfile, tmpfile.name, shallow=False)
    if not x:
        raise Exception("'%s' and '%s' do not match" % (localfile, tmpfile.name))


if __name__ == "__main__":
   cfg = config()
   #print(cfg) or sys.exit()
   runtest(cfg.port, cfg.file, cfg.user, cfg.password)
