#!/usr/bin/perl

if ( -e "/etc/opensc.conf" ){
	$openscconf = "/etc/opensc.conf";}
elsif ( -e "/etc/opensc/opensc.conf" ) {
        $openscconf = "/etc/opensc/opensc.conf"; }
elsif ( -e "/usr/local/etc/opensc.conf" ) {
        $openscconf = "/usr/local/etc/opensc.conf"; }
else {
        print "Could not be able to find out the location of opensc.conf. Please you must configure it manually";
        exit 0 
}


$openscconfceres = $openscconf.".ceres";
$previousopenscconf = $openscconf.".ceresbak";

system("cp", $openscconf, $previousopenscconf);
system("cp", $openscconf, $openscconfceres);

open(OPENSC,$openscconf);
open(BUFFER,">".$openscconfceres);

@filecontent=<OPENSC>;
$i=0;

while($i <= $#filecontent){

	$content=$filecontent[$i];

	if ($content=~/card_drivers\ \=\ ceres\;/){
		$i++;
		$content=$filecontent[$i];
        }

       	if ($content=~/card_driver\ ceres\ \{/){
	         while($filecontent[$i] !~ '\}')
                {
                        $i++;
                }
                $i++;
                $content=$filecontent[$i];
	}
 
       	if ($content=~/pkcs15init\ ceres\ \{/){
		  while($filecontent[$i] !~ '\}')
                {
                        $i++;
                }
                $i++;
                $content=$filecontent[$i];
     
	}
 

	print BUFFER $content;
	$i++;
}

close(OPENSC);
close(BUFFER);

system("mv", $openscconfceres, $openscconf);
system("rm", $previousopenscconf);
print "File opensc.conf updated succesfully!\n";

