#!/usr/bin/env perl
#*************************************************************************
# Copyright (c) 2012 UChicago Argonne LLC, as Operator of Argonne
#     National Laboratory.
# Copyright (c) 2002 The Regents of the University of California, as
#     Operator of Los Alamos National Laboratory.
# SPDX-License-Identifier: EPICS
# EPICS BASE is distributed subject to a Software License Agreement found
# in file LICENSE that is included with this distribution.
#*************************************************************************
#
# Author: Kay-Uwe Kasemir
# Date: 1-30-97

use strict;

use FindBin qw($Bin);
use lib ("$Bin/../../lib/perl");

use Getopt::Std;
use File::Basename;
use EPICS::Path;
use EPICS::Release;
use Text::Wrap;

my $tool = basename($0);

our ($opt_h, $opt_q, $opt_t, $opt_s, $opt_c);
our $opt_o = 'envData.c';

$Getopt::Std::OUTPUT_HELP_VERSION = 1;
$Text::Wrap::columns = 75;

HELP_MESSAGE() unless getopts('ho:qt:s:c:') && @ARGV == 1;
HELP_MESSAGE() if $opt_h;

my $config   = AbsPath(shift);
my $env_defs = AbsPath('../env/envDefs.h');

# Parse the ENV_PARAM declarations in envDefs.h
# to get the param names we are interested in
#
open SRC, '<', $env_defs
    or die "$tool: Cannot open $env_defs: $!\n";

my @vars;
while (<SRC>) {
    if (m/LIBCOM_API\s+extern\s+const\s+ENV_PARAM\s+([A-Za-z_]\w*)\s*;/) {
        push @vars, $1;
    }
}
close SRC;

# A list of configure/CONFIG_* files to read
#
my @configs = ("$config/CONFIG_ENV", "$config/CONFIG_SITE_ENV");

if ($opt_t) {
    my $config_arch_env = "$config/os/CONFIG_SITE_ENV.$opt_t";
    push @configs, $config_arch_env
        if -f $config_arch_env;
}

my @sources = ($env_defs, @configs);

# Get values from the config files
#
my (%values, @dummy);
readRelease($_, \%values, \@dummy) foreach @configs;
expandRelease(\%values);

# Get values given on the command-line
#
$values{EPICS_BUILD_COMPILER_CLASS} = $opt_c if $opt_c;
$values{EPICS_BUILD_OS_CLASS} = $opt_s if $opt_s;
$values{EPICS_BUILD_TARGET_ARCH} = $opt_t if $opt_t;

# Regex's for checking parameter values
my $qstr = qr/ " [^"]* " /x;
my $quoted_str = qr/ $qstr (?: \s+ $qstr )* /x;

my $ansi_colors = qr/(?:RED|GREEN|YELLOW|BLUE|MAGENTA|CYAN|BOLD|UNDERLINE)/;
my $color_esc = qr/ ANSI_ESC_ (?: $ansi_colors | RESET ) /x;
my $color_macro = qr/ ANSI_ $ansi_colors \s* \( \s* $quoted_str \) /x;
my $color_or_str = qr/ $quoted_str | $color_esc | $color_macro /x;
my $colored_str = qr/ $color_or_str (?: \s+ $color_or_str )* /x;

foreach my $var (@vars) {
    if (exists $values{$var}) {
        my $valid_str = $var eq 'IOCSH_PS1' ? $colored_str : $quoted_str;
        if ($values{$var} !~ m/^ $valid_str $/x) {
            my $quoted = qq("$values{$var}");
            die "$tool: Value set for parameter '$var' is invalid:\n",
                "    $values{$var}\n"
                unless $quoted =~ m/^ $valid_str $/x;
            $values{$var} = $quoted;
        }
    }
    else {
        warn "$tool: No value given for parameter '$var'\n";
        $values{$var} = '""';
    }
}

print "Generating $opt_o\n" unless $opt_q;

# Start creating the output
#
open OUT, '>', $opt_o
    or die "$tool: Cannot create $opt_o: $!\n";

my $sources = join "\n", map {" *   $_"} @sources;

print OUT << "END";
/* Generated file $opt_o
 *
 * Created from
$sources
 */

#include <stddef.h>
#define epicsExportSharedSymbols
#include "envDefs.h"
#include "errlog.h"

END

# Define a default value for each named parameter
#
printf OUT "const ENV_PARAM %s =\n".
      "              {\"%s\", %s};\n",
      $_, $_, $values{$_} foreach @vars;

# Also generate the list of all defined parameters
#
print OUT "\n",
    "const ENV_PARAM* env_param_list[] = {\n",
    wrap('    ', '    ', join(', ', map("&$_", @vars), 'NULL')),
    "\n};\n";
close OUT
    or die "$tool: Can't close $opt_o: $!\n";

sub HELP_MESSAGE {
    print STDERR "Usage: $tool [options] configure\n",
        "  -h       Help: Print this message\n",
        "  -q       Quiet: Only print errors\n",
        "  -o file  Output filename, default is $opt_o\n",
        "  -t arch  Target architecture \$(T_A) name\n",
        "  -s os    Operating system \$(OS_CLASS)\n",
        "  -c comp  Compiler class \$(CMPLR_CLASS)\n",
        "\n";

    exit 1;
}
