#!/usr/local/bin/perl

# This script changes absolute path names as still required by dosfop
# define the variables below and start the script

## first try to find the new values
$newManualRoot = `pwd`;
chomp $newManualRoot;
if (!defined($ENV{OCSSRC})) {
  die "$0: set environment variable OCSSRC to root of Opal source tree";
};
 $newLibRoot = $ENV{OCSSRC} . "/lib";

## read the old values
$conf="$newManualRoot/DOSFOP/Toplevel.config";
open (CONFIG, $conf) or die "$0: could not open $conf";
while(<CONFIG>) {
  if (/USER_GLOBAL/) {
    $_ = <CONFIG>;
    if (/.*directory *= *(.*)/) {
      $oldManualRoot = $1;
      last;
    } else {
      die "$0: could not determine \$oldManualRoot from $conf";
    };
  };
}
close CONFIG;


# print "oldManualRoot = $oldManualRoot\n";
# print "newManualRoot = $newManualRoot\n";
# print "oldLibRoot = $oldLibRoot\n";
# print "newLibRoot = $newLibRoot\n";

## don't do anything superfluous
#if ($oldManualRoot eq $newManualRoot and $oldLibRoot eq $newLibRoot) {exit 0;};

@configFilesMan = ("$newManualRoot/DOSFOP/Toplevel.config");
@configFilesLib = <$newManualRoot/DOSFOP/*subsystems.config>;

foreach $f (@configFilesMan) {
  if ($f eq "$newManualRoot/DOSFOP/config" and (! -e $f)) {next;};
  open (INFILE, $f) or die "$0: could not open $f";
  open (OUTFILE, ">$f.bak") or die "$0: could not open $f.bak";
  while (<INFILE>) {
    s /$oldManualRoot/$newManualRoot/g;
    print OUTFILE
  }
  close INFILE;
  close OUTFILE;
  unlink $f;
  rename "$f.bak", "$f";
}

foreach $f (@configFilesLib) {
  open (CONFIG, $f) or die "$0: could not open $f";
  while(<CONFIG>) {
    if (/name =/) {
      $_ = <CONFIG>;
      if (m!.*directory *= *(.*/src/lib)!) {
	$oldLibRoot = $1;
	last;
      } else {
	die "$0: could not determine \$oldLibRoot from '$f`";
      };
    };
  }
  close CONFIG;
  if (!($oldLibRoot eq $newLibRoot)) {
    open (INFILE, $f) or die "$0: could not open $f";
    open (OUTFILE, ">$f.bak") or die "$0: could not open $f.bak";
    while (<INFILE>) {
      s /$oldLibRoot/$newLibRoot/g;
      print OUTFILE
    }
    close INFILE;
    close OUTFILE;
    unlink $f;
    rename "$f.bak", "$f";
  };
}
