"""
Copyright (c) 2008, Bradley Dean <bjdean@bjdean.id.au>

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the <ORGANIZATION> nor the names of its contributors may
   be used to endorse or promote products derived from this software without
   specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import sys
import getopt
import os.path
import ConfigParser

import S3

# Data chunk size
#chunk_size = 10 * 1024 * 1024
chunk_size = 1

def usage():
  print "\n".join([
      'Usage:'
    , '%s [options]' % sys.argv[0]
    , ''
    , ' --read  | -r        Read mode'
    , ' --write | -w        Write mode'
    , ' --tag   | -t <tag>  Backup tag'
    , ''
    ])

def process_cmdline_options():
  """ Process command line options

      Exceptions will be thrown if invalid options are given
  """
  try:
    opts, args = getopt.getopt( sys.argv[1:]
                              , "rwt:"
                              , [ "read"
                                , "write"
                                , "tag="
                                ]
                              )
  except getopt.GetoptError, err:
    # print help information and exit:
    print str(err)
    usage()
    sys.exit(2)

  mode  = None
  tag   = None
  for opt, arg in opts:
    if opt in ("-r", "--read"):
      assert mode == None, 'Cannot read and write at the same time'
      mode = 'READ'
    elif opt in ("-w", "--write"):
      assert mode == None, 'Cannot read and write at the same time'
      mode = 'WRITE'
    elif opt in ("-t", "--tag"):
      tag = arg
    else:
      assert False, "unhandled option"

  return { 'mode' : mode
         , 'tag'  : tag
         }

def read_config():
  """ Read configuration file for this script
  """
  config_locs = [ '/usr/local/etc/s3config.cfg'
                , '/etc/s3conf/s3config.cfg'
                , os.path.expanduser('~/.s3conf/s3config.cfg')
                ]
 
  cfg = ConfigParser.ConfigParser()
  cfg.read(config_locs) 

  return cfg

def build_s3_conn(cfg):
  """ Build a connection to Amazon S3 using config file
      for credentials

      Exceptions will be thrown if information is missing
  """
  s3_conn \
    = S3.AWSAuthConnection( cfg.get('Credentials', 'aws_access_key_id')
                          , cfg.get('Credentials', 'aws_secret_access_key') )

  return s3_conn

def read_data(cmdopts, cfg, conn):
  """ Read data from STDIN and store it to Amazon S3
  """
  bucket  = cfg.get('Bucket', 'id')
  tag     = cmdopts['tag']

  assert bucket in [x.name for x in conn.list_all_my_buckets().entries]

  for name in [x.key for x in conn.list_bucket(bucket).entries]:
    if ( name[:len(tag)+1] == '%s-' % tag ):
      data = conn.get(bucket, name)
      sys.stdout.write(data.object.data)

def delete_data(cmdopts, cfg, conn):
  """ Delete existing backup data for current tag
  """
  bucket  = cfg.get('Bucket', 'id')
  tag     = cmdopts['tag']

  assert bucket in [x.name for x in conn.list_all_my_buckets().entries]

  for name in [x.key for x in conn.list_bucket(bucket).entries]:
    if ( name[:len(tag)+1] == '%s-' % tag ):
      print "Deleting old data: ", name,
      sys.stdout.flush()
      conn.delete(bucket, name)
      print "[DONE]"
      sys.stdout.flush()

def write_data(cmdopts, cfg, conn):
  """ Read data from STDIN and store it to Amazon S3

      Exceptions will be raised for non-recoverable errors
  """
  bucket  = cfg.get('Bucket', 'id')
  tag     = cmdopts['tag']
  counter = 0

  chunk = sys.stdin.read(chunk_size)
  while len(chunk) > 0:
    s3_chunk = '%s-%010d' % (tag, counter)
    print "Uploading chunk: ", s3_chunk,
    sys.stdout.flush()
    resp = conn.put(bucket, s3_chunk, chunk)
    assert resp.http_response.status == 200, resp.message
    print "[DONE]"
    sys.stdout.flush()
    counter += 1
    chunk = sys.stdin.read(chunk_size)

