#!/home/product/code/webui-perl/bin/perl -I /home/product/code/firmware/current/lib/perl5

# Barracuda Exntensible feature to handle licensing advance features
# Copyright @ 2013 Barracuda Networks

use Barracuda::Environment;
use Barracuda::ExtensibleFeatures;
use Barracuda::Config;
use Getopt::Long;
use LWP::UserAgent;

use constant CERT_DIR => "/etc/barracuda/features";

# Server Configuration
# Check with multiple update dns and port to
# retrieve update license
my $ports = {
    80 => { id => 1 },
    8000 => { id => 2 },
};

my $updhosts = {
    'updates.cudasvc.com' => {
        order => 1,
        id => 3,
        ip => '64.235.147.16',
    },
    'update10.barracudanetworks.com' => {
        order => 2,
        id => 1,
        ip => '216.129.105.129',
    },
    'update01.barracudanetworks.com' => {
        order => 3,
        id => 2,
        ip => '205.158.110.60',
    },
};

my $list = '';
my $check = '';
my $commit = '';
my $cleanup = '';
my $help = '';
GetOptions( 'list' => \$list,
            'check' => \$check,
            'commit' => \$commit,
            'cleanup' => \$cleanup,
            'help' => \$help );

# Taken from config_read code
sub usage {
    my $usage;

    $usage = "Usage: barracuda-efa options \n"
           . "  --list       list all certificate files\n"
           . "  --check      fetch list of certificate from update server and update appliance\n"
           . "  --commit     run reload to apply certificate changes\n"
           . "  --cleanup    look for expired certificates and remove them\n"
           . "  --help       Print usage help\n";

    return $usage;
}

# Takes a hash and prints it in a neat format
sub print_cert {
    my $certificate = shift;

    foreach my $feature (sort keys %$certificate) {
        print "Feature: $feature\n";
        foreach my $params (sort keys %{$certificate->{$feature}}) {
            my $value = $certificate->{$feature}{$params};
            if( ref($value) eq 'HASH' ) {
                print ucfirst($params) . "\n";
                foreach my $sub_param (sort keys %$value) {
                    print "\t". ucfirst($sub_param). ": $value->{$sub_param}\n";
                }
            } else {
                print ucfirst($params) . ": $certificate->{$feature}{$params}\n";
            }
        }
        print "\n";
    }
}

# Get the serial number - Taken from version.pl, figured this was the best place to figure out how to get the appliance serial
sub get_serial {
    my $serial = undef;
    # first try /etc/barracuda/serial
    my $serial_file = '/etc/barracuda/serial';
    if (-f $serial_file && open(SERIAL, $serial_file)) {
        $serial = <SERIAL>;
        $serial =~ s/\D//g;
        close(SERIAL);
        return $serial;
    }
    else {
        warn "Couldn't open serial file '$serial_file': $!";
    }
    # If there's more than one machine file, choose the most recently modified
    my $machine_file = (sort { -M $a <=> -M $b } glob("/root/machine*"))[0];
    if( $machine_file && open (MACHINE, $machine_file)) {
        while (<MACHINE>) {
            /serial_number\s+(\d+)/ && do {
                $serial = $1;
                last;
            };
        }
        close (MACHINE);
    } else {
        $machine_file ||= '';
        warn "Can't open machine file '$machine_file': $!";
    }
    return $serial;
}

if( $list ) {
    my $list = Barracuda::ExtensibleFeatures::get_features();
    print_cert($list);
} elsif ( $check ) {
    my $ua = LWP::UserAgent->new;
    $ua->timeout(10);
    $ua->env_proxy;

    my @errors;
    my $serial = get_serial();
    foreach my $host (sort { $updhosts->{$a}{order} <=> $updhosts->{$b}{order} } keys %$updhosts) {
        foreach my $port (sort keys %$ports) {
            # TODO need to replace the url with the correct one for licensing
            #my $base_url = 'http://updates.barracudacentral.com/cgi-bin/get_ng_license.cgi?serial=';
            my $base_url = "http://$host:$port/cgi-bin/get_ng_license.cgi?serial=";
            $base_url .= $serial;
            my $response = $ua->get($base_url);
            if (!$response->is_success) {
                push(@errors, { host => $base_url, error => $response->status_line } );
                $base_url = "http://$updhosts->{$host}{ip}:$port/cgi-bin/get_ng_license.cgi?serial=" . $serial;
                $response = $ua->get($base_url);
                if (!$response->is_success) {
                    push(@errors, { host => $base_url, error => $response->status_line } );
                    next;
                }
            }
            my $content = $response->decoded_content;
            # Parse the list of certificates using look-around matching to keep the match
            my @certificates = split(/(?<=-----END CERTIFICATE-----\n)/, $content);

            # Make sure our features directory exists
            my $features_dir = CERT_DIR;
            if(!-x $features_dir){
                system("/usr/bin/sudo /bin/mkdir $features_dir -m 755");
                system("/usr/bin/sudo /bin/chown root:root $features_dir");
            }

            # Loop through certificate.
            # Check if certificate already exist. If so, do nothing.
            # If it doesn't add it.
            my $updated = 0; # flag to check if there were any certificate updated
            foreach my $cert (@certificates) {
                my $certificate = Barracuda::ExtensibleFeatures::parse_feature($cert);

                next if ( !$certificate ); # Invalid certificate, public-key did not match

                # Kind of clunky to work with but parse_feature returns a hash with the values
                foreach my $feature (keys %$certificate) {
                    my $file_path = "/tmp/$certificate->{$feature}{filename}";
                    my $file_dest = CERT_DIR . "/$certificate->{$feature}{filename}";

                    # If the certificate does not exist, write the certificate to the valid location
                    unless ( -e $file_dest ) {
                        $updated = 1;
                        # Remove old matching certificate
                        my $current_certs = Barracuda::ExtensibleFeatures::get_features();
                        my @match_features = grep /^$feature$/, (keys %$current_certs);
                        my @match_files = map { CERT_DIR . "/" . $current_certs->{$_}{filename} } @match_features;
                        # Removing the old license
                        foreach my $file (@match_files) {
                            my $cmd = "/usr/bin/sudo /bin/rm -f $file";
                            system($cmd);
                        }

                        # Store the certificate in the license directory
                        open(FILE, ">", $file_path );
                        print FILE $cert;
                        close(FILE);
                        system("/usr/bin/sudo /bin/cp -f $file_path $file_dest");
                        system("/usr/bin/sudo /bin/rm $file_path");

                        # Touch the file to allow UI to display feature
                        my $feat_file = $feature;
                        my $features_dir = CERT_DIR;
                        $feat_file =~ s/\s/\\ /g;
                        system("/usr/bin/sudo /bin/touch $features_dir/$feat_file");
                    }
                }
            }

            exit 0 if (!$updated);
            # Touch the /etc/barracuda/trial file to notify trial period is over
            system("/usr/bin/sudo touch /etc/barracuda/trial");
            exit 1;
        }
    } # foreach

    print "Errors: \n";
    foreach (@errors) {
        print "Error: $_->{error}, Host: $_->{host}\n";
    }
    exit 0; # return 0; no update has happen
} elsif ( $commit ) {
    # call reload
    system('/usr/bin/sudo reload');
} elsif ( $cleanup ) {
    # ADC doesn't really use this feature to cleanup the certs dir.
    # Certificates always remain in the directory and is only removed upon collisions during update
    # Loop through CERT_DIR and look for expired certificates and delete them.
    my $cur_features = Barracuda::ExtensibleFeatures::get_features();
    my $cur_time = time;
    foreach my $feature (keys %$cur_features) {
        my $status = Barracuda::ExtensibleFeatures::get_status($feature);
        if ( $status eq "EXPIRED" || $status eq "INVALID" ) {
            my $cmd = "/usr/bin/sudo /bin/rm -f /etc/barracuda/features/$cur_features->{$feature}{filename}";
            system($cmd);

            # Touch the file to allow UI to display feature
            my $feat_file = $feature;
            my $features_dir = CERT_DIR;
            $feat_file =~ s/\s/\\ /g;
            system("/usr/bin/sudo /bin/rm -f $features_dir/$feat_file");
        }
    }
} elsif ( $help ) {
    print usage();
} else  {
    print usage();
}
