#!/usr/local/bin/perl -w

# jrock: perl to dump everything about mps digitals

# first do this:
#      . /usr/local/lcls/epics/setup/oracleSetup.bash
# before running this perl script

use DBI qw(:sql_types);
use Switch;

my $MICRO;

#===============================================================
sub db_connect 
#===============================================================
{
    #connect to database
    my $dbh;

    # Look up connection parameters in external db.properties file.
    # If a decryption key has been supplied, use blowfish algorithm
    # to decrypt the contents of the file.
    # SLACDEV NOW HAS MANUALLY UPDATABLE TABLES, FOR THIS PROJECT!

    my $db_host = "slac-oracle02";
    my $db_database = "SLACDEV";
    my $db_user = "nlcdev";
    my $db_password = "do~higgs3";

    # Get db vendor-specific DBI connect string
    my $dsn = get_dbi_dsn($db_database, $db_host);

    eval {
        $dbh = DBI->connect($dsn,$db_user,$db_password,
                            {AutoCommit=>0, RaiseError=>1, PrintError=>0,
                             FetchHashKeyName=>'NAME_lc'});
    };
    if ($@) {
        print "Unable to connect to db $@\n";
        print "Exiting...\n";
        exit;
    }

    return $dbh;
}

#===============================================================
sub get_dbi_dsn 
#===============================================================
{
    my $db_database = $_[0];
    my $db_host = $_[1];

    return "DBI:Oracle:$db_database";
}

#===============================================================
sub addLeadingZero($)
#===============================================================
{
   my $inStr = shift;
   $strLen = length $inStr;

   if (($strLen == 0) || ($strLen > 1))
      { return $inStr; }

   return "0" . $inStr;
}

#===============================================================
sub rpad($$)
#===============================================================
{
   my $strToPad = shift;
   my $len = shift;

   # print "RPAD: $strToPad\n";
   my $blanks = "                                                                       ";

   my $currLen = length($strToPad);
   if ($currLen < $len)
      { $strToPad .= substr($blanks, 1, ($len-$currLen)); }

   return $strToPad;
}
   
#===============================================================
sub getModuleType($)
#===============================================================
{
   my $mUnit = shift;

   if ($mUnit eq "") { return; }

   my ($moduleType,$moduleUnit) = split/:/, $mUnit;

   return $moduleType;
}

#===============================================================
sub outputTops ()
#  dev area unit attr lims1 lims2 scal1 scal2 egu
#===============================================================
{
    # CAMACFILE
    # IDOM
    # PPOM
    # DOMCHAN
    # IDOMMOD
    # PPOMMOD

   print CAMACFILE "# camac info\n";
   print CAMACFILE "file ../../Common/camacModule.template\n";
   print CAMACFILE "{\n";
   print CAMACFILE "pattern { MICRO,  CRAT, SLOT,  CRLOC, MODEL, NSLOT, NCHAN  }\n";

   print IDOMMOD "# IDOM module info\n";
   print IDOMMOD "file ../../DigitalOut/idomModule.template\n";
   print IDOMMOD "{\n";
   print IDOMMOD "pattern { MICRO,  CRAT, SLOT  }\n";

   print PPOMMOD "# PPOM module info\n";
   print PPOMMOD "file ../../DigitalOut/ppomModule.template\n";
   print PPOMMOD "{\n";
   print PPOMMOD "pattern { MICRO,  CRAT, SLOT  }\n";

   print IDOM "# 1bit IDOM info\n";
   print IDOM "file ../../DigitalOut/digitalOut1BitPulseIDOM.template\n";
   print IDOM "{\n";
   print IDOM "pattern { ";
   print IDOM "PRIM, ";
   print IDOM "LOCA, ";
   print IDOM "UNIT, ";
   print IDOM "ATTR, ";
   print IDOM "DPRIM, ";
   print IDOM "MICRO, ";
   print IDOM "DUNIT, ";
   print IDOM "DNAME, ";
   print IDOM "CRAT, ";
   print IDOM "SLOT, ";
   print IDOM "ADDR, ";
   print IDOM "BITB, ";
   print IDOM "NAM, ";
   print IDOM "PULSE, ";
   print IDOM "CHAN, ";
   print IDOM "INPB ";
   print IDOM "}\n";

   print PPOM "# 1bit PPOM info\n";
   print PPOM "file ../../DigitalOut/digitalOut1BitPulsePPOM.template\n";
   print PPOM "{\n";
   print PPOM "pattern { ";
   print PPOM "PRIM, ";
   print PPOM "LOCA, ";
   print PPOM "UNIT, ";
   print PPOM "ATTR, ";
   print PPOM "DPRIM, ";
   print PPOM "MICRO, ";
   print PPOM "DUNIT, ";
   print PPOM "DNAME, ";
   print PPOM "CRAT, ";
   print PPOM "SLOT, ";
   print PPOM "NAM, ";
   print PPOM "CHAN, ";
   print PPOM "INPB ";
   print PPOM "}\n";

   print DOMCHAN "# DOM channel info\n";
   print DOMCHAN "file ../../DigitalOut/domChannel.template\n";
   print DOMCHAN "{\n";
   print DOMCHAN "pattern { MICRO,  CRAT, SLOT,  CHAN,  ALIAS0, ALIAS1  }\n";
}

#===============================================================
sub outputEnds ()
#===============================================================
{
    # CAMACFILE
    # IDOM
    # PPOM
    # DOMCHAN

   print CAMACFILE "}\n\n";
   print IDOMMOD "}\n\n";
   print PPOMMOD "}\n\n";
   print IDOM "}\n\n";
   print PPOM "}\n\n";
   print DOMCHAN "}\n\n";

}

#===============================================================
# main code starts here
#===============================================================
print "STARTING\n";

if ($#ARGV < 1) { die "Please specify cvs filename and micro!\n"; }

   die "Could not open csv file\n" unless (open(CSV, $ARGV[0]));
   $MICRO = $ARGV[1];

   print "generating files for micro $MICRO from file $ARGV[0]\n";

   my @lines = <CSV>;
   my $line;
   close(CSV);

   $TFname = $MICRO . "camacModuleDig" . ".substitutions";
   die "Could not open $TFname\n" unless (open(CAMACFILE, '>'.$TFname));

   $TFname = $MICRO . "idomModule" . ".substitutions";
   die "Could not open $TFname\n" unless (open(IDOMMOD, '>'.$TFname));

   $TFname = $MICRO . "ppomModule" . ".substitutions";
   die "Could not open $TFname\n" unless (open(PPOMMOD, '>'.$TFname));

   $TFname = $MICRO . "digitalOut1BitPulseIDOM" . ".substitutions";
   die "Could not open $TFname\n" unless (open(IDOM, '>'.$TFname));

   $TFname = $MICRO . "digitalOut1BitPulsePPOM" . ".substitutions";
   die "Could not open $TFname\n" unless (open(PPOM, '>'.$TFname));

   $TFname = $MICRO . "domChannel" . ".substitutions";
   die "Could not open $TFname\n" unless (open(DOMCHAN, '>'.$TFname));

   my $lineCount = 0;
  
   outputTops;

   my $currMicro = "none";
   my $currSprim = "none";
   my $currSunit = "none";
   my $currcomponent = "none";
   my $compNum = 0;
   my $stateNum = 0;

   my $moduleType = "none";

   my $currNumStates = 0;
   my $currNumBits = 0;

   my $outFile;
   my $outType = "NONE";
   my $componentLine = "";
   my $componentEName = "";
   my $badComponent = 0;
   my $badMsg = "BAD MSG ";

   my %moduleHash = ();
   my %bitHash = ();
   my $i;

   my $moduleDescr1 = "none";
   my $bitDescr1 = "none";

   my $bit1x;
   my $bit1b;
   my $chan1;

   # bad component and bad msg is set if:
   #   - more than one bit

# there is one file-line per state, so multiple file-lines per component
# file is sorted by: micro, prim, unit, component, value1 (so that for 1 bit 2 state components, the 0 will come first)
# (i.e. ZNAM before ONAM)
### PROCESS EACH INPUT LINE ###
   foreach $line (@lines)
      {
      ++$lineCount;
      if ($lineCount == 1)
         { next; }
      chomp $line;
      #print "$line\n";

# new:
      my($IorO,$micro,$Sprim,$Sunit,$component,$stateStr,$Eprim,$Elocation,$Eunit,$attribute,$EState,$in_use,$numStates,$IOString,$SevrPls,$numBits,$Munit1,$crate1,$slot1,$bit1,$value1,$Munit2,$crate2,$slot2,$bit2,$value2,$Munit3,$crate3,$slot3,$bit3,$value3) = split/,/, $line;

      # first things first: add leading 0's to slot
      $slot1 = addLeadingZero($slot1);
      $chan1 = addLeadingZero($bit1);
      #$slot2 = addLeadingZero($slot2);
      #$slot3 = addLeadingZero($slot3);
      print "SLOTS $slot1\n";

      # create mod 16 hex bits
      $bit1x = 0;
      $bit1x = sprintf("%X", $bit1%16);
      $bit1b = 2**($bit1%16);
     
      if (!($bit2 eq "")) { $bit2x = sprintf("%X", $bit2%16); } else { $bit2x = 0; }
      if (!($bit3 eq "")) { $bit3x = sprintf("%X", $bit3%16); } else { $bit3x = 0; }
      # print "HEX BITS $bit1x $bit2x $bit3x\n";

print "READ: $micro $Sprim $Sunit\n";
      # process only outputs
      # csv file must be sorted by In-or-Out
#      if ($IorO eq "OUT")
      # skip if OUTPUT, or if not the micro of current interest, or in_use is not yes
      if ($IorO eq "INP")
         { print "input chan; skipping\n"; next; }
      if (!($micro eq $MICRO))
         { print "not doing this micro now; skipping\n"; next; }
      if ($in_use eq "NO")
         { print "not in use; skipping\n"; next; }
       
print "Processing...\n";
# outputs are simpler:  they are all one bit, and there is one substitutions line per line of
# the file.  So, no need to accumulate stuff over multiple lines

         
      # flag if > 1 bit
      if ($numBits > 1)
         { $badMsg .= "more than one bit.  numBits = $numBits  "; $badComponent = 1; }

      # figure out output file
      $moduleType = getModuleType($Munit1);
      if ($moduleType eq "IDOM")
         { $outFile = *IDOM; $outType = "IDOM"; }
      elsif ($moduleType eq "PPOM")
         { $outFile = *PPOM; $outType = "PPOM"; }
      else
         { $badMsg .= "invalid module type: $moduleType "; $badComponent = 1; }


      # print "$Eprim, $Elocation, $Eunit, $component $stateStr NUM BITS: $numBits   NUM STATES: $numStates\n";

      # gather the things that are component-specific
      $currMicro = $micro;
      $currSprim = $Sprim;
      $currSunit = $Sunit;
      $currcomponent = $component;
      $currNumBits = $numBits;
      $currNumStates = $numStates;

      #for reference, from above      my($IorO,$micro,$Sprim,$Sunit,$component,$stateStr,$Eprim,$Elocation,$Eunit,$attribute,$EState,$in_use,$numStates,$IOString,$SevrPls,$numBits,$Munit1,$crate1,$slot1,$bit1,$value1,$Munit2,$crate2,$slot2,$bit2,$value2,$Munit3,$crate3,$slot3,$bit3,$value3) = split/,/, $line;
      #example: OUT,LI17,ACCC,16,DC,OFF,KLYS,LI17,1,FOCUSBULK_OFFCMD,OFF,YES,2,IO:I00080000:O0101,10,1,IDOM:121,1,21,1,1,,,,,,,,,,

#      $componentLine = "        { $Eprim, $Elocation, $Eunit,  $attribute, $Sprim, $micro,  $Sunit, \"$component\" "; 
      $componentEName = $Eprim . ":" . $Elocation . ":" . $Eunit . ":" . $attribute;

      ### ACCUMULATE MICRO LEVEL MODULE INFO - check and record each file line's module  ###
      # module and bit hashes are used to output this micro's idim*.substitution files at the end.
      # these hashes are accumulated for the entire micro
      # so, add to module hashes, if this is the first time we've seen this module
      # and initialize 32 spare bits for each newly encountered module
      $moduleDescr1 = "none";
      #$moduleDescr2 = "none";
      #$moduleDescr3 = "none";
      $bitDescr1 = "none";
      #$bitDescr2 = "none";
      #$bitDescr3 = "none";

      my $moduleDescr1 = $micro . ":" . $crate1 . ":" . $slot1;
      # print "MODULE1 : $moduleDescr1\n";
      if (!(defined $moduleHash{$moduleDescr1}))
         { 
         $moduleHash{$moduleDescr1} = $moduleType; 
         for ($i=0; $i<32; ++$i)
            {
            my $bitDescr = $moduleDescr1 . ":" . $i . ":0";
            $bitHash{$bitDescr} = "SPARE";
            $bitDescr = $moduleDescr1 . ":" . $i . ":1";
            $bitHash{$bitDescr} = "SPARE";
            }
         }

      # addr macro
      my $addr1 = 0;
      #my $addr2 = 0;
      #my $addr3 = 0;

      if ($bit1 < 16) { $addr1 = 0; } else { $addr1 = 1; }

      # state-specific info.

      $bitDescr1 = $moduleDescr1 . ":" . $bit1 . ":" . $value1;
      $bitHash{$bitDescr1} = $componentEName;

      # print "STATESTR DEBUG *$stateStr*  *$EState*\n";
      # first crate/module/slot/addr/bitnum for each bit
      # output all bit1 info
      # BIT 1 loc


      if ($moduleType eq "IDOM")
         {
         $componentLine = "        { $Eprim, $Elocation, $Eunit,  $attribute, $Sprim, $micro,  $Sunit, \"$component\" "; 
         $componentLine .= ", $crate1, $slot1, $addr1, $bit1b "; 

         # then this state and pulse
         $componentLine .= ", \"$EState\", $SevrPls, $chan1 "; 

         # values of the bit
         $componentLine .= ", $value1 "; 
         }
      else
         {
         $componentLine = "        { $Eprim, $Elocation, $Eunit,  $attribute, $Sprim, $micro,  $Sunit, \"$component\" "; 
         $componentLine .= ", $crate1, $slot1 "; 

         # then this state and pulse
         $componentLine .= ", \"$EState\", $chan1 "; 

         # values of the bit
         $componentLine .= ", $value1 "; 
         }
 

      # then, output the component, or error message if it is BAAAD for some reason.
      if ($badComponent == 1)
         { print "BAD COMPONENT! $currMicro $currSprim $currSunit $currcomponent:  $badMsg\n"; }
      else
         { print $outFile "$componentLine }\n"; }
    }

    # now we're done with the components and states
    # output the list of crates, slots, addresses, and bit assignments
    for my $key ( keys %moduleHash ) 
       {
       # print "MODULEHASH $key\n";
       my ($modMicro, $modCrate, $modSlot) = split/:/, $key;
       my $mType = $moduleHash{$key};

       print CAMACFILE "        { $modMicro,  $modCrate, $modSlot,  \"LOCA\", \"$mType\", 1, 32  }\n";
       if ($mType eq "IDOM")
          { print IDOMMOD   "        { $modMicro,  $modCrate, $modSlot }\n"; }
       else
          { print PPOMMOD   "        { $modMicro,  $modCrate, $modSlot }\n"; }

       for ($i=0; $i<32; ++$i)
          {
          # print "BITHASH $bitDescr IS $bitHash{$bitDescr}\n";
          # add leading 0 to channel if needed
          my $bitDescr0 = $key . ":" . $i . ":0";
          my $bitDescr1 = $key . ":" . $i . ":1";
          my $iChan = addLeadingZero($i);
          print DOMCHAN "        { $modMicro,  $modCrate, $modSlot,  $iChan, $bitHash{$bitDescr0}, $bitHash{$bitDescr1} }\n";
          }
       }

#    if (!$dbh) {
#        $dbh = db_connect();
#    }

#    $dbh->rollback();
#    $dbh->disconnect();


   outputEnds;

   close CAMACFILE;
   close IDOM;
   close PPOM;
   close DOMCHAN;

   print "Done\n";

