#!/usr/bin/perl
##
##  00DEV/editspec -- Edit .spec files in OpenPKG CVS repository
##  Copyright (c) 2000-2001 Cable & Wireless Deutschland GmbH
##  Copyright (c) 2000-2001 Ralf S. Engelschall <rse@engelschall.com>
##
##  Permission to use, copy, modify, and distribute this software for
##  any purpose with or without fee is hereby granted, provided that
##  the above copyright notice and this permission notice appear in all
##  copies.
##
##  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
##  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
##  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
##  IN NO EVENT SHALL THE AUTHORS AND COPYRIGHT HOLDERS AND THEIR
##  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
##  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
##  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
##  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
##  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
##  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
##  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
##  SUCH DAMAGE.
##

if ($#ARGV == -1) {
    print STDERR "Usage: $0 <cmd> [<cmd> ...] [-- <pkg> [<pkg> ...]]\n";
    exit(1);
}

my @cmd = ();
my @pkg = ();
my $iscmd = 1;
foreach my $arg (@ARGV) {
    if ($iscmd and $arg eq '--') {
        $iscmd = 0;
        next;
    }
    if ($iscmd) {
        push(@cmd, $arg);
    }
    else {
        push(@pkg, $arg);
    }
}
if ($#pkg == -1) {
    foreach my $pkg (glob("*")) {
        next if (not -d $pkg or not -f "$pkg/$pkg.spec");
        push(@pkg, $pkg);
    }
}

my $all = 0;
foreach my $p (@pkg) {
    print "Package $p:\n";
    next if (not -d $p or not -f "$p/$p.spec");

    open(SPEC, "<$p/$p.spec") || die;
    my $spec = '';
    $spec .= $_ while (<SPEC>);
    close(SPEC);

    $_ = $spec;
    foreach $cmd (@cmd) {
        eval $cmd;
    }

    if ($spec ne $_) {
        $spec = $_;
        open(SPEC, ">$p/$p.spec.new") || die;
        print SPEC $spec;
        close(SPEC);
        system("diff -u1 $p/$p.spec $p/$p.spec.new");
        my $ok;
        if ($all) {
            $ok = "yes";
        }
        else {
            print "Edit [a(ll)/Y(es)/n(o)]: ";
            $ok = <STDIN>;
        }
        if ($ok =~ m/^(?:A|a)(?:ll)?\n?$/s) {
            $ok = "yes";
            $all = 1;
        }
        if ($ok =~ m/^(?:Y|y)(?:es)?\n?$/s or $ok eq '') {
            # $spec =~ s|(\nRelease:\s+)(\d+)|$1 . sprintf("%d", $2+1)|se;
            print "Ok: Edited $p/$p.spec\n";
            open(SPEC, ">$p/$p.spec") || die;
            print SPEC $spec;
            close(SPEC);
        }
        unlink("$p/$p.spec.new");
    }
}

