#!/usr/bin/perl
#
# Copyright information and license terms for this software can be
# found in the file LICENSE that is included with the distribution
#

use strict;
use warnings;

use Getopt::Std;
use Cwd qw(getcwd);

our ($opt_o, $opt_4, $opt_B, $opt_h);

$Getopt::Std::OUTPUT_HELP_VERSION = 1;
&HELP_MESSAGE if !getopts('o:4:B:h:');

$opt_4 = getcwd()
    unless $opt_4 && -d $opt_4;
$opt_B = $ENV{EPICS_BASE}
    unless $opt_B;
die "Path to EPICS_BASE not known\n"
    unless $opt_B && -d $opt_B;
$opt_h = $ENV{EPICS_HOST_ARCH}
    unless $opt_h;
$opt_o = "RELEASE.$opt_h.Common"
    unless $opt_o;

# The list of dependencies in @ARGV contains duplicates,
# and we want only the *last* mention of each module.
my %seen;
my @uniques = reverse grep {!$seen{$_}++} reverse @ARGV;

my @depends = map {
    warn "Module $_ not found in $opt_4\n"
        unless -d "$opt_4/$_";
    my $name = uc $_;
    $name =~ s/CPP$//;
    "$name = $opt_4/$_";
} @uniques;
my $depends = join "\n", @depends;

open (my $OUT, '>', $opt_o)
    or die "Can't create $opt_o: $!\n";

print $OUT <<"EOF";
# $opt_o
#   Generated by $opt_4/tools/genRelease.pl
$depends
EPICS_BASE = $opt_B
EOF
close $OUT
    or die "Can't close $opt_o: $!\n";


sub HELP_MESSAGE {
    print STDERR <<EOF;
Usage:
    genRelease.pl [-o outfile] [-4 epicsv4] [-B base] [-h arch] dependencies...
EOF
    exit 2;
}
