#!/usr/bin/perl

# Usage: 
#         
# arg1 = -o q         query existing driver statement in /etc/X11/XF86config   
#           m         modify driver string with string specified in -d 
#           l         list supported drivers in /opt/hsc/data/.graphics  
#           c         compare driver name to list in /opt/hsc/data/.graphics
#                     0=success=match found  1=fail=not in list
#
# arg2 = -d <string>  name of driver. Only valid with -m and -c
#
#

use Getopt::Std;
my $operation;
my $drivername;

my $debug=0;

#MAIN
my $targetfile = '/etc/X11/XF86Config';
my $tmptargetfile = '/tmp/XF86Config';
my $supportedfile = '/opt/hsc/data/.graphics';

if ($#ARGV <= 0) {
      usage();
      exit (0);
}

getopts("o:d:", \%options);

$operation= $options{o};
$drivername= $options{d};
chomp($drivername);
if ($operation eq 'q' ) {
    query_driver();
} elsif ($operation eq 'l' ) {
    get_list();
} elsif ($operation eq 'm') {
       if ($drivername ne "") {
               change_file();
       }else {
              usage();
              exit (0);
      }   
} elsif ($operation eq 'c') {
       if ($drivername ne "") {
               my $rc_code = check_list($drivername);
               if ( $rc_code == 0) {
                      if ($debug == 1) { print "main :invalid driver $drivername\n"; }
                      exit (1); 
               } else {
                       if ($debug == 1) { print "main :found valid driver $drivername\n"; }
                       exit (0);
               }
      }else {
         usage();
         exit (0);
      }   
} else {
   usage();

exit (0);
}
#End MAIN 

   
sub query_driver
{
  if ($debug == 1) {print "in query_driver\n";}
  open(FILE,"<$targetfile") || print("ERROR:Cannot open file $targetfile\n");

  # Initialize stuff
  $startSearch = 0;
  $startString = "configured by xf86config";
  while ($line=<FILE>) {

      if ($line =~ m/$startString/i) {
            $startSearch = 1;  # Set toggle to start real work
      }

      if ($startSearch == 1) {
            if ($line =~ m/Driver/i) {
                 $line =~ m/"([^"]*)"/;
                 print STDOUT "$1\n";
                 exit(0);
            }
      }
  }
  
}

#Prints the first field in the supported driver list to stdout
sub get_list
{
  $counter=0;
  open(FILE,"<$supportedfile") || print STDERR "ERROR:Cannot open file $supportedfile\n";
  while ($line=<FILE>) {

       if ( $counter != 0) {
               print STDOUT "," ;
       }
       @fields = split(/:/,$line);
       chomp($fields[0]);
       print STDOUT "$fields[0]";
       $counter++;
  }
 print STDOUT "\n";
}

sub check_list
{
  my $found=0; 
  my $search_string=$_[0];

  if ($debug == 1) { print ">> enter check_list"; }
  @fields = (); #clear
  open(CHECKFILE,"<$supportedfile") || print STDERR "ERROR:Cannot open file $supportedfile\n";
  while ($nextline=<CHECKFILE>) {
       @fields = split(/:/,$nextline);
       chomp($fields[0]);
       $driverfromlist  = $fields[0];
       if ($debug == 1) { print ">> in check_list  list.  entry $driverfromlist  passed in  $search_string\n"; }
       if ($driverfromlist eq $search_string) {
           
	   if ($debug == 1) {print ">> in check_list  set found to 1\n"; }
           $found=1;
           #read in the arguements
           foreach (0..$#fields) {
                 chomp($fields[$_]);
                 if ($debug == 1) { print ">> list fields value $fields[$_]\n"; 
                               print ">> list fields index $_\n"; }
                 close (CHECKFILE);
                 return $found;
            }
       } 
  }
  close (CHECKFILE);
  if ($debug == 1) { print ">> leave check_list"; }
  return $found;
}

sub change_file
{

  if ($debug) { print "> in change_file\n"; }

  #is valid drivername passed in
  my $mfound = check_list($drivername);
  if ( $mfound == 0) {
      if ($debug == 1) { print ">Invalid driver name\n";}
      exit (1);
  }
  
  # store the new driver data for later use 
  my @new_fields = @fields;

  # Initialize stuff
  open(FILE,"<$targetfile") || print STDERR "ERROR:Cannot open file $targetfile\n";
  open(OUTFILE,">$tmptargetfile") || print STDERR "ERROR:Cannot open file $targetfile\n";
  $startSearch = 0;
  $startString = "configured by xf86config";
  $endSection = "EndSection";

  while ($line=<FILE>) {

      if ($line =~ m/$startString/i) {
            $startSearch = 1;  # Set toggle 
      }

      if ($startSearch == 1) {
            if ($line =~ m/Driver/i) {
                            
                 $line =~ m/"([^"]*)"/;
                 if( $1 eq $drivername ) {
                     #Stop now. new driver = existing driver. nothing to do 
                     if ($debug == 1) {print(">Stop now. new driver  $drivername = existing driver $1.\n "); }
                     close(OUTFILE);
                     system("rm $tmptargetfile");
                     exit (0);
                 }    

                 #get the old driver data, in case we need to delete some parms.    
                 $olddrivername = $1; 
                 $mfound = check_list($olddrivername);
                 if ( $mfound == 0) {
                         if ($debug == 1) {print ">Invalid driver name\n"; }
                         exit (1); 
                 }
                 @old_fields = @fields;

                 #modify the driver entry 
                 $line =~ s/$olddrivername/$drivername/;
                 if ($debug == 1) {print "> modified line is :  $line\n";}

                 #Add addtional params to the file, for the new driver.
                 my $x = @new_fields;
                 if ($x > 1) {
                    print OUTFILE "$line"; #first print the last buffer
                    for ($i=1; $i<$x; $i++) {
                       if ($debug == 1) {print "> change_files new fields  $i  $new_fields[$i]\n"; }
                       $line = "    $new_fields[$i]";
                       # Print all params, but the last. the while loop will take care of that
                       if ( $i+1 != $x ) { 
                              print OUTFILE "$line"; 
                       } 
                    }            
                 }

                 my $x = @old_fields;
                 if ( $x > 1) {
                       #If the old driver had some custom params, remove
                       #to avoid confusing the new driver  
                        $startSearch = 2;
                 }else {
                       #Done, just write the rest of the file
                        $startSearch = 0;
                 }
           }
      }

      if ($startSearch == 2) {
            if ($line =~ m/$endSection/i) {
                           $startSearch = 0;  # Done, stop looking, Set toggle 
            }
 
             my $x = @old_fields;
             for ($i=0; $i<$x; $i++) {
                    if ($line =~ m/$old_fields[$i]/i) {
                    
                      if ($debug == 1) {print " change_files old_fields $i  $old_fields[$i]\n"; }
                      $line = "#   $line";
                    }
             }
                 

      }
      print OUTFILE "$line" ;
  }
  close(OUTFILE);
  system("cp $tmptargetfile $targetfile");
  system("rm $tmptargetfile");
     
  exit (0);
}


sub usage
{
   print "Usage: [-o q|l]\n";
   print "Usage: [-o m|c] [-d drivername]\n";
}
