summaryrefslogtreecommitdiff
path: root/bin/ups
blob: 2de9dfb73e89b077c809862f9b6a19d0c3d883ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/python3
# ups.khirnov.net uploader

import argparse
import os.path
import shutil
import subprocess
import sys

try:
    import magic
    have_magic = True
except ImportError:
    have_magic = False

server    = 'https://ups.khirnov.net/'
cert_path = os.path.expanduser('~/.local/var/up/cert')

parser = argparse.ArgumentParser()
parser.add_argument('-n', '--name')
parser.add_argument('path', nargs = '?', default = '-')

args = parser.parse_args()

if args.path == '-' and not args.name:
    src_name = '-'
    dst_name = args.name or 'stdin'

    # try to guess the extension when name is not provided
    if not args.name and have_magic:
        m = magic.Magic(extension = True)
        e = m.from_buffer(sys.stdin.buffer.peek(2048))
        if e != '???':
            dst_name += '.' + e.split('/')[0]
else:
    src_name = args.path
    dst_name = args.name or os.path.basename(src_name)

stdin = subprocess.PIPE if src_name == '-' else subprocess.DEVNULL

curl_cmdline = ['curl', '--silent', '--show-error', '--cert', cert_path,
                '--data-binary', '@' + src_name, server + dst_name]

child = subprocess.Popen(curl_cmdline, stdin = stdin)
if stdin != subprocess.DEVNULL:
    # stream our stdin to the child process
    # cannot pass stdin to the child directly because we peeked at it above
    shutil.copyfileobj(sys.stdin.buffer, child.stdin)
    child.stdin.close()

ret = child.wait()
if ret != 0:
    sys.stderr.write('curl returned an error code: %d\n' % ret)
else:
    sys.stdout.write('\n')