#!/home/product/code/webui-perl/bin/perl

# This file will backpropagate the bcrypt settings of this firmware to the
# "revert" firmware, if it is capable of supporting it.

my $previous;

BEGIN {
    $previous = "/home/product/code/firmware/previous";
    # in a begin block just to maximize the speed with which we exit
    # this script if it is not appropriate
    if (!-e $previous) {
        print STDERR "Not backpropagating bcrypt because there's no previous firmware\n";
        exit 0;
    }
    if (!-e "$previous/lib/perl5/Login/Password.pm") {
        print STDERR "Not backpropagating bcrypt because there's no bcrypt support in the previous firmware\n";
        exit 0;
    }
    my $variables;
    open $variables, "<", "$previous/lib/perl5/MS_variable.pm" or die;
    local $/;
    my $varfile = <$variables>;
    # Assume that if it already had bcrypt annotations in it, it is correct.
    if ($varfile =~ /bcrypt/) {
        print STDERR "Not backpropagating bcrypt because the previous firmware already has it set up.\n";
        exit 0;
    }

    # if we make it past all that, then the "previous" firmware A: has the
    # code to support bcrypt but B: doesn't have any variables set to turn
    # it on.
}

use MS_variable;

my @bcrypts;

for my $var (keys %MS_variable::variable) {
    if ($MS_variable::variable{$var}->{bcrypt}) {
        push @bcrypts, $var;
    }
}

if (!@bcrypts) {
    exit(0);
}

my $variables = join(' ', @bcrypts);

my $contents = <<'FIX_BCRYPT';
package Barracuda::Config::Variable::BcryptFixup;
use strict;
use warnings;

# This is a file autogenerated by postinstall, meant to fix up previous
# firmwares to have their bcrypt flag set up if the user reverts.

sub load_variables {
    my $vars = shift;
    for my $variable (qw(__VARIABLES__)) {
        $vars->{$variable}->{bcrypt} = 1;
    }
}

sub load_files {
    # deliberately do nothing
}

1;
FIX_BCRYPT

# we know the variable names are all words, numbers, and _:
$contents =~ s/__VARIABLES__/$variables/;

# Note we are going to deliberately overwrite the previous content of this
# file. If the user upgraded, reverted, then upgraded to a different
# version of the firmware that has different variables set, we want to go
# ahead and put the new stuff in.
my $fixup_file;
open $fixup_file, ">",
    "/home/product/code/firmware/previous/lib/perl5/Barracuda/Config/Variable/BcryptFixup.pm"
    or die;
print $fixup_file $contents;
close $fixup_file;

exit(0);

