#!/usr/bin/env oo-ruby
#--
# Copyright 2010 Red Hat, Inc.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#++

def usage
  puts <<USAGE
== Synopsis

#{$0}: Extract a backup of this configuration
  This command must be run as root.

== Usage

#{$0} --file [filename]

== List of arguments
  -f|--file                 filename    File containing backup (stdin if not specified)
  -n|--dry-run                          Don't make changes, just do a dry run
  -q|--porcelain                        TODO: what does this do?
  -d|--debug                            Enable debug mode
  -h|--help                             Print this message

USAGE
  exit 255
end

require 'json'
require 'zlib'
require 'base64'

require 'rubygems'
require 'openshift-origin-node'
opts = GetoptLong.new(
    ["--file",                "-f", GetoptLong::REQUIRED_ARGUMENT],
    ["--dry-run",             "-n", GetoptLong::NO_ARGUMENT],
    ["--porcelain",           "-q", GetoptLong::NO_ARGUMENT],
    ["--debug",               "-d", GetoptLong::NO_ARGUMENT],
    ["--help",                "-?", GetoptLong::NO_ARGUMENT]
)

filename = nil
begin
  opts.each do |k, v|
    case k
    when '--help'
      usage
    when '--file'
      filename = v
    when '--dry-run'
      $dry_run = true
    when '--debug'
      $oo_debug = true
    when '--porcelain'
      $porcelain = true
    else
      usage
    end
  end
rescue GetoptLong::Error => e
  usage
end


if filename.nil? or (filename == "") or (filename == "-")
  blob = $stdin.read
else
  File.open(filename, 'r') do |f|
    blob = f.read
  end
end

begin
  OpenShift::FrontendHttpServer.json_create({ 'data' => JSON.parse(blob) })
rescue OpenShift::FrontendHttpServerExecException => e
  $stderr.puts(e.message + e.stdout + e.stderr)
  exit e.rc
rescue OpenShift::FrontendHttpServerException => e
  $stderr.puts(e.message)
  exit 129
rescue Exception => e
  $stderr.puts(e.message)
  exit -1
end
exit 0
