#!/usr/bin/python3
# vim: tabstop=4 expandtab

import argparse, os, subprocess

parser = argparse.ArgumentParser(description='upload data on file mirror',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument('-c', '--check', action='store_true',
    help='check download and verify data')
parser.add_argument('-l', '--limit', nargs='?', default='80',
    help='limit upload bandwith (rsync --bwlimit))')
parser.add_argument('-u', '--url', default='https://xmw.de/',
    help='download url base')
parser.add_argument('-d', '--destination', default='michael@spot:~/web',
    help='rsync destination base')
parser.add_argument('-p', '--path', default='tmp',
    help='path (rsync and download)')
parser.add_argument('-r', '--rsync', 
    default=['-avP', '--no-g', '--chmod=ug=rw,o='],
    help='rsync options w/o bwlimit')
parser.add_argument('-v', '--verbose', action='store_true',
    help='print rsync command')
parser.add_argument('-n', '--dry-run', action='store_true',
    help='don\'t do anything')
parser.add_argument('-x', '--xclip', action='store_true',
    help='copy links to xclip -in')
parser.add_argument('file', nargs='+',
    help='file to upload')

args = parser.parse_args()

rsync_opt = args.rsync
if args.dry_run:
    rsync_opt.append('--dry-run')
if args.limit != '0':
    rsync_opt.append('--bwlimit')
    rsync_opt.append(args.limit)

cmd = ['rsync'] + rsync_opt + \
    args.file + \
    [os.path.join(args.destination, args.path)]

if args.verbose:
    print(cmd)
url = os.path.join(args.url, args.path)
links = ' '.join(map(lambda s: os.path.join(url, os.path.basename(s)), args.file))
print(links)
r = subprocess.Popen(cmd)
print(r.wait())
if not args.dry_run and args.xclip:
    x = subprocess.Popen(['xclip', '-in'], stdin=subprocess.PIPE)
    x.stdin.write(links.encode('utf-8'))
    x.stdin.close()
    x.wait()

