#!/usr/bin/env python
import sys
import os
import boto
import yaml

CONFIG_FILE_NAME = 'aws-config.txt'
aws_config = dict()
s3 = None

# use the config file to connect to s3.
if os.path.exists(CONFIG_FILE_NAME):
    config_file = open('aws-config.txt', 'r')
    aws_config = yaml.safe_load(config_file)
    config_file.close()
    s3 = boto.connect_s3(aws_config['access_key_id'],
                         aws_config['secret_access_key'])
else:
    s3 = boto.connect_s3()

# if no args, just list the buckets.
if len(sys.argv) == 1:
    rs = s3.get_all_buckets()
    for key in rs:
        print key.name
    sys.exit(0)

# if we have args (that is, we're here), they're either buckets to list the
# contents of, or files to download.

for bucket_spec in sys.argv[1:]:

    bucket_name = None
    object_name = None

    if '/' in bucket_spec:
        # we have a bucket and an object. Split on the first slash.
        bucket_name, object_name = bucket_spec.split('/', 1)
    else:
        bucket_name = bucket_spec

    if s3.lookup(bucket_name) is None:
        print "No such bucket: %s" % bucket_name
        sys.exit(1)

    bucket = s3.get_bucket(bucket_name)

    if object_name is None:
        # list the bucket contents.
        rs = bucket.list()
        for key in rs:
            if not key.name.endswith('/'):
                print "%s/%s" % (bucket_spec, key.name)
        sys.exit(0)

    key = bucket.get_key(object_name)

    if key is None:
        print "No such object: %s" % object_name
        sys.exit(1)

    path, filename = os.path.split(object_name)
    key.get_contents_to_filename(filename)
