#!/usr/bin/env python3

import sys
import requests
import argparse
import os
import yaml

from textwrap import dedent

try:
    with open(f'{os.path.expanduser("~")}/.sshare.yml') as fh:
        config = yaml.safe_load(fh)['sshare']
except FileNotFoundError:
    config = {}

ap = argparse.ArgumentParser()

ap.add_argument('FILE', help='File to share ("-" for stdin [text])')

ap.add_argument('-u',
                '--url',
                help='Service URL',
                default=config.get('url', 'http://localhost:8008'))

ap.add_argument('-k',
                '--key',
                help='upload key',
                default=config.get('upload-key'))

ap.add_argument('-T',
                '--timeout',
                help='timeout',
                default=config.get('timeout', 5),
                type=int)

ap.add_argument('-s',
                '--one-shot',
                help='One-shot sharing',
                action='store_true')

ap.add_argument('-x', '--expires', help='Expiration (in seconds)', type=int)

a = ap.parse_args()

headers = {}
if a.key:
    headers['X-Auth-Key'] = a.key

data = {}

if a.one_shot:
    data['oneshot'] = 1

if a.expires:
    data['expires'] = a.expires

if a.FILE == '-':
    files = {'file': ('paste.txt', sys.stdin, 'text/plain')}
else:
    files = {'file': open(a.FILE, 'rb')}

fname = 'STDIN' if a.FILE == '-' else os.path.basename(a.FILE)

print(f'{fname} -> {a.url}')

r = requests.post(f'{a.url}/u',
                  files=files,
                  data=data,
                  headers=headers,
                  timeout=a.timeout)

if not r.ok:
    raise RuntimeError(f'Server response code: {r.status_code}')

print(
    dedent(f"""
        {fname} uploaded

        Access URL: {r.headers["Location"]}
        Expires: {r.headers["Expires"]}
        """))

if a.one_shot:
    print('(Single access attempt allowed)')
    print()
