#!/usr/bin/env ruby
#
# s3sync - Tool belt for managing your S3 buckets
#
# The MIT License (MIT)
#
# Copyright (c) 2013  Lincoln de Sousa <lincoln@clarete.li>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

$:.unshift(File.dirname(__FILE__) + '/../lib') unless $:.include?(File.dirname(__FILE__) + '/../lib')

require "s3sync/exceptions"
require "s3sync/config"
require "s3sync/cli"

conf = S3Sync::Config.new

# Time to load config and see if we've got everything we need to cook our salad
begin
  conf.read
rescue S3Sync::NoConfigFound => exc
  # We can't proceed without having those two vars set
  $stderr.puts "You didn't set up the following environment variables:"
  $stderr.puts
  exc.missing_vars.each {|var| $stderr.puts "   * #{var}"}
  $stderr.puts

  $stderr.puts "I tried to load a config file from the following paths:"
  $stderr.puts
  exc.paths_checked.each {|path| $stderr.puts "   * #{path}"}
  $stderr.puts

  $stderr.puts "You could try to set the `S3SYNC_PATH' environment variable"
  $stderr.puts "pointing to a file to be loaded as your config file or just"
  $stderr.puts "export those variables to your environment like this:"
  $stderr.puts
  exc.missing_vars.each {|var|
    $stderr.puts "    $ export #{var}=<value-provided-by-amazon>"
  }
  $stderr.puts
  $stderr.puts "Learn how to do that here: https://github.com/clarete/s3sync"
  exit
end

# Step aside, the star of this show is here. Let's try to create the
# environment to run the requested command. And feed the user back if
# information needed was not enough
begin
  S3Sync::CLI::run conf
rescue S3Sync::FailureFeedback => exc
  $stderr.puts exc.message
  exit 1
rescue S3Sync::WrongUsage => exc
  $stderr.puts "Error:\n  #{exc.msg}\n" if exc.msg
  exit exc.error_code
rescue Interrupt
  $stderr.puts "Interrupted"
  exit 1
end