#!/usr/bin/perl

#
# Copyright (C) 2019 Nethesis S.r.l.
# http://www.nethesis.it - nethserver@nethesis.it
#
# This script is part of NethServer.
#
# NethServer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# NethServer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NethServer.  If not, see COPYING.
#

use strict;
use esmith::ConfigDB;
use esmith::event;
use JSON;

require '/usr/libexec/nethserver/api/lib/helper_functions.pl';

my $eventName = 'nethserver-vsftpd-save';
my @eventArgs = ();
my $ret;
my $exitCode = 0;
my $db = esmith::ConfigDB->open('accounts');

my $input = readInput();
my $cmd = $input->{'action'};

if ($cmd eq 'update') {
    foreach (qw(Chroot ChrootDir Password Description)) {
        $db->set_prop($input->{'name'}, $_, $input->{$_});
    }
} elsif ($cmd eq 'configuration') {
    my $cdb = esmith::ConfigDB->open();
    $cdb->set_prop('vsftpd', 'status', $input->{'status'});
} elsif ($cmd eq 'enable') {
    $db->set_prop($input->{'name'}, 'status', 'enabled');
} elsif ($cmd eq 'disable') {
    $db->set_prop($input->{'name'}, 'status', 'disabled');
} else {
    error();
}

esmith::event::set_json_log(1);

if(esmith::event::event_signal($eventName, @eventArgs)) {
    $ret = {'state' => 'success'};
} else {
    $ret = {
        'type' => 'Error',
        'message' => 'common.api_update_failed',
        'attributes' => {
            'event_name' => $eventName,
            'event_args' => \@eventArgs,
        }
    };
    $exitCode = 1;
}

print encode_json($ret);
exit($exitCode);
