#!/usr/bin/perl

use strict;
use warnings;

use Getopt::Long qw(:config posix_default no_ignore_case);
use List::Util qw(none);
use YAML::XS;

my ($progname) = $0 =~ m{(?:.*/)?([^/]*)};

my $cfg = '/etc/ngcp-config/constants.yml';
my $db = '/var/lib/snmp/snmpd.conf';

sub usage
{
    print <<HELP;
Usage: $progname [<options>...] <username>

Options:
      --help              Display this help text.
HELP
}

sub error
{
    my @args = @_;

    print { \*STDERR } "error: @args\n";
    exit 1;
}

sub update_persistent_config
{
    my $user = shift;

    # Delete the user from the persistent configuration file. We assume this
    # is a user that has not been created in the /etc config file, which will
    # not match the username anyway.
    system { 'ngcp-service' } qw(ngcp-service stop snmpd);

    open my $ifh, '<', $db
        or error("cannot read persistent snmpd config $db: $!");
    open my $ofh, '+>', "$db.new"
        or error("cannot create new persistent snmpd config $db.new: $!");

    while (my $line = <$ifh>) {
        my @columns = split ' ', $line;

        if (!(@columns && $columns[0] eq 'usmUser' && $columns[6] eq $user)) {
            print { $ofh } $line;
        }
    }

    close $ofh
        or error("cannot write into new persistent snmpd config $db.new: $!");
    close $ifh;

    rename "$db.new", $db
        or error("cannot renamed $db.new into $db: $!");

    system { 'ngcp-service' } qw(ngcp-service start snmpd);

    return;
}

my @opts_spec = (
    'help' => sub { usage(); exit 0; },
);

GetOptions(@opts_spec);

if (@ARGV != 1) {
    error("expects a single username");
}

my $user = shift;

my $yaml = YAML::XS::LoadFile($cfg);

if (none { $_->{u} eq $user } @{$yaml->{credentials}{snmpd}{users}}) {
    error("user $user does not exist");
}

update_persistent_config($user);

$yaml->{credentials}{snmpd}{users} = [
    grep {
        $_->{u} ne $user
    } @{$yaml->{credentials}{snmpd}{users}}
];

YAML::XS::DumpFile($cfg, $yaml);

system { 'ngcpcfg' } 'ngcpcfg', 'apply', "Delete SNMP $user";

1;
