#!/usr/bin/env ruby
# Copyright 2011 Red Hat, Inc.
#
# 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.

require 'rhc-common'

#
# print help
#
def p_usage
    rhlogin = get_var('default_rhlogin') ? "Default: #{get_var('default_rhlogin')}" : "required"
    puts <<USAGE

Usage: #{$0}
Pull down application snapshot for a user

  -l|--rhlogin   rhlogin    Red Hat login (RHN or OpenShift login with OpenShift Express access) (#{rhlogin})
  -a|--app                  Target application to snapshot (required)
  -r|--restore              Local path of the tarball to restore (restores git and application data folders found in archive)
  -s|--save                 Local path to save tarball (default: ./$APPNAME.tar.gz)
  -p|--password  password   RHLogin password (optional, will prompt)
  -d|--debug                Print Debug info
  -h|--help                 Show Usage info
  --config  path            Path of alternate config file
  --timeout #               Timeout, in seconds, for connection

USAGE
exit 255
end

begin
    opts = GetoptLong.new(
        ["--debug", "-d", GetoptLong::NO_ARGUMENT],
        ["--help",  "-h", GetoptLong::NO_ARGUMENT],
        ["--app",  "-a", GetoptLong::REQUIRED_ARGUMENT],
        ["--save",  "-s", GetoptLong::REQUIRED_ARGUMENT],
        ["--restore",  "-r", GetoptLong::REQUIRED_ARGUMENT],
        ["--rhlogin",  "-l", GetoptLong::REQUIRED_ARGUMENT],
        ["--config", GetoptLong::REQUIRED_ARGUMENT],
        ["--password",  "-p", GetoptLong::REQUIRED_ARGUMENT],
        ["--timeout", GetoptLong::REQUIRED_ARGUMENT]
    )
    opt = {}
    opts.each do |o, a|
        opt[o[2..-1]] = a.to_s
    end
rescue Exception => e
  #puts e.message
    p_usage
end

# If provided a config path, check it
check_cpath(opt)

# Pull in configs from files
libra_server = get_var('libra_server')
debug = get_var('debug') == 'false' ? nil : get_var('debug')

if opt["help"] || !opt['app']
    p_usage
end

if opt["debug"]
    debug = true
end
RHC::debug(debug)

RHC::timeout(opt["timeout"] ? opt["timeout"] : get_var('timeout'))

opt["rhlogin"] = get_var('default_rhlogin') unless opt["rhlogin"]

if !RHC::check_rhlogin(opt['rhlogin'])
    p_usage
end

password = opt['password']
if !password
  password = RHC::get_password
end

user_info = RHC::get_user_info(libra_server, opt['rhlogin'], password, @http, debug, false)

app = opt['app']
opt['save'] = "#{opt['app']}.tar.gz" unless opt['save'] || opt['restore']

unless user_info['app_info'][app]
    puts
    puts "Could not find app '#{app}'.  Please run rhc-user-info to get a list"
    puts "of your current running applications"
    puts
    exit 101
end

app_uuid = user_info['app_info'][app]['uuid']
namespace = user_info['user_info']['namespace']
rhc_domain = user_info['user_info']['rhc_domain']
if opt['save']
  ssh_cmd = "ssh #{app_uuid}@#{app}-#{namespace}.#{rhc_domain} 'snapshot' > #{opt['save']}"
  puts "Pulling down a snapshot to #{opt['save']}"
else
  if File.exists? opt['restore']
    `tar -tf #{opt['restore']} './*/#{app}'`
    if $?.exitstatus != 0
      puts "Archive at #{opt['restore']} does not contain the target application: ./*/#{app}"
      puts "If you created this archive rather than exported with rhc-snapshot, be sure"
      puts "the directory structure inside the archive starts with ./<app_uuid>/"
      puts "i.e.: tar -czvf <app_name>.tar.gz ./<app_uuid>/"
      exit 255
    else
      `tar -tf #{opt['restore']} './*/git'`
      include_git = $?.exitstatus == 0
      ssh_cmd = "cat #{opt['restore']} | ssh #{app_uuid}@#{app}-#{namespace}.#{rhc_domain} 'restore#{include_git ? ' INCLUDE_GIT' : ''}'"
      puts "Restoring from snapshot #{opt['restore']}"
    end
  else
    puts "Archive not found: #{opt['restore']}"
    exit 255
  end
end


puts 
puts ssh_cmd if debug
output = `#{ssh_cmd}`
puts
if $?.exitstatus != 0
    puts output
    puts
if opt['save']
    puts "Error in trying to save snapshot.  You can try to save manually by running:"
else
    puts "Error in trying to restore snapshot.  You can try to restore manually by running:"
end
    puts
    puts ssh_cmd
    puts
    exit 1
end
puts output if opt['restore'] && debug
exit 0
