#!/usr/bin/perl

#
# editconfig.pl: Holds routines used by some scripts
# to manipulate config files.
#

require '/usr/lib/localization-config/common/log.pl';

# Return 0 if the file wasn't changed and 1 if the file was updated
sub AppendIfMissingLine {
    my ($filename, $line) = @_;
    my $updated = 0;

    my @lines;
    if (open(FILE, "<$filename")) {
        @lines = <FILE>;
        close(FILE);
    }

    $line .= "\n";

    if ( ! grep /^$line$/, @lines ) {
        $updated = 1;
        push(@lines, $line);
    }

    if ($updated) {
        log_msg("$0: Updating $filename");
        open(FILE, ">$filename.new") || log_die("$0: Unable to write $filename.new");
        print FILE @lines;
        close(FILE);
        rename "$filename.new", $filename;
    }
    return $updated;
}

# Return 0 if nothing changed, and 1 if the file was updated
sub UpdateOrAppendVariable {
    my ($filename, $variable, $content, $delimeter, $section, $prefix) = @_;
    my $updated = 0;
    my $newline;
    if (defined($prefix)) {
        $newline = "\t";
    }
    $newline .= "$variable$delimeter$content\n";

    my @lines;
    if (open(FILE, "<$filename")) {
        @lines = <FILE>;
        close(FILE);
    }

    if (defined($section)) {
        if (! grep /\[$section\]/, @lines ) {
            $updated = 1;
            push(@lines, "\[$section\]\n");
        }
    }
    
    if (grep /$variable.*$delimeter/, @lines ) {
        @lines = map { if ($_ =~ m/$variable.*$delimeter/ && ! ($_ =~ /$variable.*$content/) )
                       { $updated = 1;
                         $newline; }
                       else
                       { $_; }
                   } @lines;
    } else {
        if (defined($section)) {
            $newline = "\[$section\]\n".$newline;
            @lines = map { if ($_ =~ m/^\[$section\]/ )
                        { $updated = 1;
                            $newline; }
                        else
                        { $_; }
                    } @lines;
        } else {
            $updated = 1;
            push(@lines, $newline);
        }
    }
    
    if ($updated) {
        log_msg("$0: Updating $filename");
        open(FILE, ">$filename.new") || log_die("$0: Unable to write $filename.new");
        print FILE @lines;
        close(FILE);
        rename "$filename.new", $filename;
    }
    return $updated;
}

1;