#!/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("connect")
    dirnum=0
    dirname="tmp"
    while c.exists(dirname):
       dirnum += 1
       dirname = "tmp.%s" % dirnum
    print("exists")
    c.mkdir(dirname)
    print("mkdir '%s'" % (dirname,))
    filename = "file"
    tmpfile = tempfile.NamedTemporaryFile()

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

    # 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)
