#!/usr/bin/perl
use strict;
use warnings;

use lib "/opt/sarch/common/lib";
use lib "/opt/sarch/fw/bin/perl";
use lib "/opt/sarch/om/bin/perl/OMIface";

use NextCAM::Servicing::Client;
use ObjectManagementService;
use FwIface::Types;
use Getopt::Std;

# Parse cmd line
my %args = ();
getopts("h:p:", \%args);

my $host = $args{h} || "s_master";
my $port = $args{p} || 10000;
my $cmd  = $ARGV[0];

# Create instance of OM client
sub create {
    my $service_client = NextCAM::Servicing::Client->new($host, $port)
			or die "unable to create servicing client instance\n";
    my $proto = $service_client->getProtocol("skm.om")
		or die "unable to get proto for 'skm.om'\n";
    my $om_client = ObjectManagementServiceClient->new($proto)
		    or die "unable to create OM client\n";
    return $om_client;
}

# check status
sub status {
    return shift->getServiceStatus();
}

# start OM service
sub start {
    my $client = shift;
    my $status = $client->getServiceStatus();
    if($status ne ServiceStatus::STARTING && $status ne ServiceStatus::RUNNING) {
	$client->startup();
    }
}

# stop OM service
sub stop {
my $client = shift;
    my $status = $client->getServiceStatus();
    if($status ne ServiceStatus::STOPPING && $status ne ServiceStatus::STOPPED) {
	$client->shutdown();
    }
}

sub main {
     unless(defined $cmd && $cmd =~ /^start|stop|status/) {
	print "Usage: $0 start|stop|status\n";
	return;
    }
    eval {
	my $client = create();
	for($cmd) {
	    /start/ && do { start($client) };
	    /stop/ && do { stop($client) };
	    /status/ && do { print status($client)."\n" };
	}
    };
    if ($@)
    {
	if($@->UNIVERSAL::isa("FwException")) {
	    die "FwException: ". $@->{errorId}.": ".$@->{what}. "\n";
	} else {
	    die "$@";
	}
    }
}

#--------------------------------------------------------
# main
main();
