#!/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 }


$openscconfdnie = $openscconf.".dnie";
$previousopenscconf = $openscconf.".dniebak";

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

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

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

while($i <= $#filecontent){

	$content=$filecontent[$i];

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

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

	print BUFFER $content;
	$i++;
}

close(OPENSC);
close(BUFFER);

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

