#!/usr/bin/env python
 # -*- coding: utf-8 -*-
"""
Generating a sharable url for a private s3 file.

Usage:
    s3url [options] <s3_object>

Options:
    -h, --help     Show this screen and exit.
    --version      Show the version and exit.
    -k <aws_keys>  AWS credentials as `YourAccessKeyId:YourSecretAccessKey`.
                   If omitted, these will be loaded from the environment
                   variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`.
    -e <time>      Time until expiration [default: 24h].
                   Examples: '1h30m', '3d', '42m37s', '5d2h6m10s'

To share `file/to/share.txt` from `my-bucket`, the <s3_object> argument
should be:
    my-bucket/file/to/share.txt

Copyright © 2014 Ford Hurley <ford.hurley@gmail.com>
This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License, Version 2,
as published by Sam Hocevar. See the COPYING file for more details.
"""
from __future__ import print_function
import sys

import docopt
import s3url


def error(message, exception):
    sys.stderr.write(message)
    sys.stderr.write('--> %r\n' % exception)
    sys.stderr.write('See the --help\n')
    sys.exit(1)


def main(s3obj, expires_in, keys):
    try:
        expires_in = s3url.time.to_seconds(expires_in)
    except ValueError as e:
        error('Invalid expiration time argument (%s)\n' % expires_in, e)

    try:
        access_key_id, secret_key = s3url.parse_keys(keys)
    except ValueError as e:
        error('Invalid credentials argument\n', e)

    try:
        bucket_name, key_name = s3url.parse_obj(s3obj)
    except Exception as e:
        error('Invalid object argument (%s)\n' % s3obj, e)

    conn = s3url.connect(access_key_id, secret_key)

    url = s3url.get_s3_url(conn, bucket_name, key_name, expires_in)

    print(url)


if __name__ == '__main__':
    args = docopt.docopt(__doc__, version=s3url.__version__)
    main(args['<s3_object>'], args['-e'], args['-k'])
