#!/usr/bin/perl

# featurelist.cpaddons file

use strict;
use CGI qw(param);

BEGIN { push @INC, '/usr/local/cpanel', '/usr/local/cpanel/whostmgr/docroot/cgi' }

use Cpanel::cPAddons;
use whmlib;

my $feat = param('feature');
my $save = param('save');

defheader("cPAddons Script Feature ($feat) Manager");

if($feat && -e "/var/cpanel/features/$feat") {
    my $allopts = Cpanel::cPAddons::_listallmods('hashref');
    my %disable;
    if(open FAD, "/var/cpanel/features/$feat.cpaddons") {
        while(<FAD>) {
            chomp;
            next if !$_;
            my($nm,$vl) = split /\=/, $_;
            $disable{$nm} = 1 if $vl eq 0;    
        }
        close FAD
    }
    for(keys %disable) {
        my(undef, $cata, $name) = split /\:\:/, $_;
        $cata =~ s/\_/ /g;
        $name =~ s/\_/ /g;
        $allopts->{$cata}->{$_} = $name;
    }
    if($save) {
        my $cont = '';
        for my $ky (sort keys %{ $allopts }) {
            next if ref $allopts->{$ky} ne 'HASH';
            for(sort keys %{ $allopts->{$ky} }) {
                $cont .= "$_=0\n" if !param($_);
            }
        }
        if(open NEW, '>', "/var/cpanel/features/$feat.cpaddons") {
            print NEW $cont;
            close NEW;
            print qq(<p>Your configuration has been saved. [<a href="$ENV{SCRIPT_NAME}?feature=$feat">Back</a>]</p>\n);
        } else {
            print "Could not save the list: $!"; 
        }
    } else {
        print qq(<p>Back to <a href="/scripts2/featuremanager?feature=$feat&action=editfeature">$feat</a></p>\n);
        print qq(<form action="$ENV{SCRIPT_NAME}" method="post">\n<input type="hidden" name="feature" value="$feat" />\n);
        
        for my $ky (sort keys %{ $allopts }) {
            next if ref $allopts->{$ky} ne 'HASH';
            for(sort keys %{ $allopts->{$ky} }) {
                my ($vend) = $_ =~ m/^(\w+)\:/;
                my $chk = exists $disable{$_} ? '' : ' checked';
                print qq(<input type="checkbox"$chk name="$_" value="1" /> $allopts->{$ky}->{$_} ($vend) <br />\n);
            }
        }
        
        print qq(<input type="hidden" name="save" value="1" />\n<input type="submit" value="Save" />\n</form>\n);
    }
} else {
    print "Sorry that feature list is invalid.";
}
