#!/usr/bin/env perl

#Copyright (c) 2020, AT&T Intellectual Property.
#All rights reserved.

use warnings;
use strict;
use lib '/opt/vyatta/share/perl5/';

use Vyatta::ConfigMgmt;
use Getopt::Long;
use Readonly;
use File::Basename;
use JSON;
use IPC::Run3;

Readonly my $SCRIPT_NAME => basename($0);

sub report_netconf_error {
    my ($message) = @_;

    my $error = ();
    $error->{'error-type'}     = "application";
    $error->{'error-severity'} = "error";
    $error->{'error-tag'}      = "operation-failed";
    $error->{'error-message'}  = $message;
    my $json = encode_json($error);
    print STDERR $json;
    exit 1;
}

# rollback_rpc handles the vyatta-config-rollback-v1:rollback RPC
sub rollback_rpc {
    my $stdin = do { local $/ = undef; <> };
    my $input = decode_json $stdin;
    my $revision = $input->{'vyatta-config-rollback-v1:revision-id'} // 1;
    my $comment  = $input->{'vyatta-config-rollback-v1:comment'}     // "";
    my $result;

    my @cmd = (
        "/opt/vyatta/sbin/lu", "-user", "configd",
        "/lib/vci-rollback-ephemeral/rollback-action",
        "$revision", "$comment"
    );

    run3( \@cmd, \undef, \undef, \$result );

    if ( $result and $result ne "" ) {
        report_netconf_error($result);
    }

    # No output for Rollback RPC
    print encode_json {};

    exit 0;
}

# get_commit_history handles the
# vyatta-config-rollback-v1:get-commit-history RPC
sub get_commit_history_rpc {
    my %history = cm_get_commit_history();
    print encode_json( \%history );
    exit 0;
}

sub call_action_by_name {
    my ( $actions, $script_name, $opt_name, $usage ) = @_;

    my $usagefn = sub {
        printf( "Usage for %s %s:\n", $script_name, $usage );
        printf( "    %s %s --%s=[%s]\n",
            $script_name, $usage, $opt_name, join( "|", keys( %{$actions} ) ) );
        exit(1);
    };

    my ($name);
    GetOptions( "$opt_name=s" => \$name, ) or $usagefn->();
    $usagefn->() unless ( defined($name) );

    my $action = $actions->{$name};
    $usagefn->() unless ( defined($action) );

    return $action->();
}

my %actions = (
    "rollback"           => \&rollback_rpc,
    "get-commit-history" => \&get_commit_history_rpc,
);
call_action_by_name( \%actions, $SCRIPT_NAME, "action", "" );
