#!/usr/bin/env oo-ruby
require 'rubygems'
require 'getoptlong'
require 'active_resource'
require 'parseconfig'

def p_usage
  puts <<USAGE
Usage: #{$0}
Register a new user.

  -l|--login       Login for admin user
  -p|--password    Password for admin user
     --username    User name for the new user
     --userpass    User password for the new user
  -h|--help        Show usage info

USAGE
exit 1
end

begin
  opts = GetoptLong.new(
                        ["--login",     "-l", GetoptLong::REQUIRED_ARGUMENT],  
                        ["--password",  "-p", GetoptLong::REQUIRED_ARGUMENT],                          
                        ["--username",        GetoptLong::REQUIRED_ARGUMENT],
                        ["--userpass",        GetoptLong::REQUIRED_ARGUMENT],
                        ["--help",      "-h", GetoptLong::NO_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 opt['help'] || !opt['login'] || !opt['password'] || !opt['username'] || !opt['userpass']
    p_usage
end

ActiveResource::Base.include_root_in_json = false
module ActiveResource
  module Formats
    #
    # The OpenShift REST API wraps the root resource element whi
    # to be unwrapped.
    #
    module OpenshiftJsonFormat
      extend ActiveResource::Formats::JsonFormat
      extend self

      def decode(json)
        decoded = super
        if decoded.is_a?(Hash) and decoded.has_key?('data')
          decoded = decoded['data']
        end
        if decoded.is_a?(Array)
          decoded.each { |i| i.delete 'links' }
        else
          decoded.delete 'links'
        end
        decoded
      end
    end
  end
end

$hostname = "localhost"
begin
  if File.exists?("/etc/openshift/node.conf")
    config = ParseConfig.new("/etc/openshift/node.conf")
    val = config["PUBLIC_HOSTNAME"].gsub(/[ \t]*#[^\n]*/,"")
    val = val[1..-2] if val.start_with? "\""
    $hostname = val
  end
rescue
  puts "Unable to determine hostname. Defaulting to localhost\n"
end

$options = opt
class Account < ActiveResource::Base
  self.site="https://#{$hostname}/broker/rest"
  self.user = $options['login']
  self.password = $options['password']
  self.format = :OpenshiftJson

  def read_errors
    error_data = JSON.parse(@remote_errors.response.body)
    error_data["messages"]
  end

  def to_json(options={})
    {"username" => username, "password" => password}.to_json(options)
  end
end

acc = Account.new(:username => opt['username'], :password => opt['userpass'])

if acc.save
  print "User created successfully\n"
else
  errors = acc.read_errors
  if errors.nil? || errors.empty?
    print "An unknown error has occured"
  else
    print "#{errors[0]["text"]}\n"
  end
end
