#!/usr/bin/perl
# Copyright (C) 2011-2013 Zentyal S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# This script removes the module configuration stored in our backend
# (normal and state) and purge SQL log tables if exists

use EBox;
use EBox::Config;
use EBox::GlobalImpl;
use EBox::Sudo;
use EBox::Util::SQL;
use TryCatch;

my ($modname) = @ARGV;

EBox::init();

cleanModuleConf($modname);
EBox::Util::SQL::dropModuleTables($modname);

my $purgeModule = "/var/lib/zentyal/purge-module/$modname";
if (EBox::Sudo::fileTest('-x', $purgeModule)) {
    try {
        EBox::Sudo::root($purgeModule);
        EBox::Sudo::root("rm -f '$purgeModule'");
    } catch {
        EBox::warn("Purge of module $modname failed");
    }
}

exit 0;

sub cleanModuleConf
{
    my ($module) = @_;

    my $global = EBox::GlobalImpl->instance();
    $global->delete_dir("global/conf/modules/$module");
    $global->{redis}->delete_dir("$module/conf");
    $global->{redis}->delete_dir("$module/ro");
    $global->{redis}->unset("$module/state");
}
