#!/usr/bin/env python

# This file is part of StorageAPI, by Luke Granger-Brown
# and is licensed under the MIT license, under the terms listed within
# LICENSE which is included with the source of this package

from storage import QueryAuth, ApiV1

if __name__ == '__main__':
    def print_help_and_quit(err=None):
        import sys
        print('%s <auth key> <command> <filename|object ID>' % (sys.argv[0],))
        print('auth key: your Storage API key')
        print('command: either "upload" or "info"')
        print('filename: a file from your harddrive to upload')
        print('object ID: an object to print information about')
        if err is not None:
            print()
            print(err)
        sys.exit(0)

    import sys
    import os.path
    if len(sys.argv) != 4:
        print_help_and_quit()

    _, auth_key, command, command_param = sys.argv
    if command not in ('upload', 'info'):
        print_help_and_quit('Command must be upload or info')
    elif len(auth_key) != 40:
        print_help_and_quit('Auth key must be 40 characters long')
    elif command == 'upload' and not os.path.exists(command_param):
        print_help_and_quit('File "%s" does not exist' % (command_param,))

    auth = QueryAuth(auth_key)
    api = ApiV1(auth)
    if command == 'upload':
        with open(command_param, 'rb') as fh:
            try:
                f = api.object_upload(fh, os.path.basename(command_param))
                print("Upload successful")
                print(" - File ID: %s" % (f.object_id,))
                print(" - File URL: %s" % (f.url,))
            except Exception as e:
                print("Upload failed")
                print(e)
    elif command == 'info':
        try:
            f = api.object(command_param)
            fi = f.info()
            print("File ID: " + fi['name'])
            print("File URL: " + f.url)
            print()
            print("Original filename: " + fi['original'])
            print("File extension:" + fi['extension'])
            print("MIME type: " + fi['mime'])
            print()
            print("Created at: " + fi['created_at'])
            print("Updated at: " + fi['updated_at'])
            print()
            print("File size (bytes): " + fi['size'])
        except Exception as e:
            print("Fetching file info failed")
            print(e)
