#! /usr/bin/perl

#----- Copyright & License -----
#
# Copyright (C) 2019 AT&T Intellectual Property.
# All Rights Reserved.
#
# SPDX-License-Identifier: GPL-2.0-only
#
#----- Copyright & License -----

# Render "system ntp keyid" into a chrony key file.
#
# chrony's key file format is
#     <id> <TYPE> <key>
# where TYPE is the hash function in upper case, and a plain text key is
# written with an ASCII: prefix so that characters which would otherwise be
# ambiguous are taken literally. ntpd's key file used lower case names and
# a bare key, hence the translation here.

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

use Getopt::Long;
use JSON qw( decode_json );
use Vyatta::Configd;

my ( $rtinstance, $path );

GetOptions( "rtinstance=s" => \$rtinstance, );

$rtinstance = 'default' unless defined $rtinstance;

if ( $rtinstance eq 'default' ) {
    $path = "system ntp keyid";
} else {
    $path = "routing routing-instance $rtinstance system ntp keyid";
}

my $cfg = Vyatta::Configd::Client->new();
my $db  = $Vyatta::Configd::Client::AUTO;

if ( $cfg->node_exists( $db, $path ) ) {
    my $subtree = decode_json $cfg->tree_get_full( $db, $path );

    my @keyids = @{ $subtree->{"keyid"} };
    for my $keyid (@keyids) {
        my $dgst = uc( $keyid->{"digest"} );
        my $pass = $keyid->{"plaintext-password"};
        my $name = $keyid->{"tagnode"};
        printf "%d %s ASCII:%s\n", $name, $dgst, $pass;
    }
}

exit 0;
