#!/usr/bin/env python

from __future__ import print_function
from os.path import expanduser
import yaml
import sys

from sendspace.rest import SendspaceRESTAPI, SendspaceRESTAPIError

if __name__ == '__main__':
    settings = {}

    try:
        with open(expanduser('~/.sendspace-api')) as f:
            settings = yaml.load(f.read())
    except IOError:
        pass

    try:
        with open(expanduser('~/.sendspace-session'), 'rb') as f:
            last_session_id = f.read().decode('utf-8').strip()
    except IOError:
        last_session_id = None

    if len(settings.items()) == 0:
        print('~/.sendspace-api must exist and be a YAML file with the following keys: api_key, username, password', file=sys.stderr)
        sys.exit(1)

    rest = SendspaceRESTAPI(settings['api_key'])
    need_login = last_session_id is None

    if last_session_id:
        try:
            rest.set_session_id(last_session_id)
        except SendspaceRESTAPIError:
            last_session_id = None

    if not last_session_id:
        session_id = rest.login(settings['username'], settings['password'])
        with open(expanduser('~/.sendspace-session'), 'w') as f:
            f.write(session_id + '\n')

    try:
        print(rest.upload_file(sys.argv[1])['url'])
    except IndexError:
        print('Usage: sendspace FILE', file=sys.stderr)
        sys.exit(1)
    except SendspaceRESTAPIError as e:
        print(e, file=sys.stderr)
        sys.exit(1)
