#! perl -w

## a toy program to just unset all CFX environment variables and then
## call another application.

# $Id$

use strict;

my @explicit_list;
if ($ARGV[0] =~ m!^-+launcher!) {
  # only unset variables which were set by the launcher script, and
  # which vary between CFX-5 versions.  This also does not include
  # the PDF directory variables, those are handled elsewhere.
  @explicit_list=qw(CFX_DATA_DIR CFX5EXECDIR CFX_CMD_DIR CFX5ROOT
                    CFX5BINDIR CUE_GLOBAL_DATA_DIR CFX5_CCL_LIBS
                    CFX5_CCL_LIBSDIR CFX5_CCL_RULESDIR
                    CFX5_CCL_RULES CFX5_CCL_PARSER CFX5LIBDIR
                    CFXBUILDID CFX_PRODUCT_FULLNAME CFX5_CUESM_EXEC
                    CFX_PRODUCT_NAME CFX_ICON_DIR CFX_CONFIG_DIR
                    CFX_SITEFILE CFX_PERL_ABI CFX_HELP_JARDIR
					CFX_LAUNCH_CFG_DIR CFX_LAUNCH_ETC_DIR CFX_LAUNCH_SCRIPT_PATH
					CUE_CHARTER_DIR CUE_CHARTVIEWER_DIR CUE_DICT CUE_EXE_DIR
					CUE_IMAGECONVERT_DIR CUE_LOCAL_DATA_DIR CUE_PIXMAP_DIR
					CUE_POSTENGINE_EXE CUE_POSTGUI_DIR CUE_POSTGUI_EXE
					CUE_PREENGINE_EXE CUE_PREGUI_DIR CUE_PREGUI_EXE CUE_DIR
					CUE_TOP_DATA_DIR CUE_VIEWER_DIR CFX_HELP_DIR CFX_EG_DIR);
  shift @ARGV;
  # we really want to do CFX5_CCL_HOSTS
  if (exists $ENV{CFX5_HOSTS_CCL}) {
    (my $aa=$ENV{CFX5_HOSTS_CCL}) =~ s![\\/]!!g;
    (my $bb=$ENV{CFX5ROOT}) =~ s![\\/]!!g;
    if ($aa =~ m!^$bb!) {
      delete $ENV{CFX5_HOSTS_CCL};
    }
  }
}

# White list of variables that should never be unset
my @white_list=qw(
    CFX_FORCE_WOW64 CFX5RSH CFX_SOLVE_DISABLE_REMOTE_CHECKS
);

my @k=keys %ENV;
for my $k (@explicit_list ? @explicit_list : @k) {
  if ($k =~ m!CFX|CUE|CFDS|CCL!) {
    my $keep = 0;
    for my $w (@white_list) {
      if ("$k" eq "$w") { $keep = 1; }
    }
    delete $ENV{$k} unless $keep;
  }
}

my @cmd=@ARGV;
(my $me=$0) =~ s!.*[\\/]!!g;

unless (@cmd) {
  print STDERR "Usage: $me <program> [<args> ...]\n";
  exit(2);
}

if ($cmd[0] =~ m!^-!) {
  # allow some switches
  if ($cmd[0] =~ m!^-+h!) {
    print STDERR "Cleans out the environment and then execs another program\n";
    print STDERR "Usage: $me <program> [<args> ...]\n";
    exit(0);
  }
  if ($cmd[0] =~ m!-+print!) {
    for my $k (keys %ENV) {
      print "$k=$ENV{$k}\n";
    }
    exit(0);
  }
  print STDERR "$me: Unrecognised switch $cmd[0]\n";
  exit(2);
}

my $exec=$cmd[0];
if ($^O eq 'MSWin32') {
  # nasty quoting of args with spaces
  @cmd=map { m! ! ? qq("$_") : $_ } @cmd;
}

unless (exec { $exec } @cmd) {
  print STDERR "$me: Exec of $cmd[0] failed: $!\n";
  exit(2);
}

