#!/usr/bin/perl 
# ------------------------------------------------------------
# Copyright 2001, 1999 Javier Fernndez-Sanguino Pea <jfs@computer.org>
# ------------------------------------------------------------
# This script adapts all config files to European
# spanish-speaking users (includes euro character support).
# Distributed under the GNU GPL license.
# ------------------------------------------------------------
# Este programa adapta todos los ficheros de configuracin para
# usuarios hispanoparlantes europeos (incluye soporte caracter euro).
# Distribuido bajo la licencia GNU.
# ------------------------------------------------------------

use Getopt::Long;
Getopt::Long::config("auto_abbrev");

GetOptions("debug:i","help","version","pregunta","config=s","quiet:i");
$only_checkfile=shift(@ARGV);

if ($opt_help) {
	print "Modo de empleo: eurocastellanizar [OPCIN] [fichero]\n";
	print "Ajusta los ficheros de configuracin del sistema para adecuarlo\n";
	print "a su uso por hispanoparlantes incluyendo tambin soporte de Euro.\n";
	print "opciones -vhp -d [x] -c directorio.\n";
	print "\tfichero\tslo adaptar el fichero indicado (si sabe cmo hacerlo)\n";
	print "\t-d,--debug\tmuestra por pantalla informacin de su progreso.\n";
	print "\t-q,--quiet\tno muestra ninguna informacin.\n";
	print "\t\tacepta argumentos, -d 2, por ejemplo, da ms depuracin.\n";
	print "\t-p,--pregunta\tpregunta antes de hacer cambios en un fichero.\n";
	print "\t-c,--config\tUtiliza un directorio alternativo para configuracin.\n";
	print "\t-h,--help\tmuestra esta informacin.\n";
	print "\t-v,--version\tinforma de la versin y finaliza.\n";
	print "\nComunicar 'bugs' al sistema de seguimiento de Bugs de Debian\n(por favor lea /usr/share/doc/debian/bug-reporting.txt\n";
	exit 0;
}

# Variables globales
$VERSION="0.18";
#$prefix="/var/lib/user-euro-es/";
$prefix=".user-euro-es.bak";
$config_dir= $opt_config || "/etc/";
$config_dir= $config_dir."/" if $config_dir !~ /\/$/;
if (defined($opt_debug)) {
        $opt_debug = 1;
} else {
        $opt_debug = 0;
}
# If we debug, then we do not want to be quiet
if (defined($opt_quiet) || $opt_debug) {
	$opt_quiet = 1 ;
} else {
	$opt_quiet = 0;
}

if ($opt_version) {
	print "eurocastellanizar versin $VERSION\n";
	exit 0;
}

my $uid = (getpwuid($<))[3];

if ( ! $opt_config  && $uid != 0 ) {
	print "ERROR: Necesita tener permisos de superusuario para ejecutar\n";
	print "este programa ya que se modifican ficheros en $config_dir\n";
	print "Abortando.\n";
	exit 1;
}

# Ficheros de configuracin y expresiones regulares
%ficheros_conf=(
	'lynx.cfg' => 's/^#?\s*PREFERRED_LANGUAGE\s*:\s*(es,)*(.*)$/PREFERRED_LANGUAGE:es,$2/;s/^#?\s*CHARACTER_SET\s*:.*$/CHARACTER_SET:iso-8859-15/;s/^#?\s*PREFERRED_CHARSET\s*:.*$/PREFERRED_CHARSET:/',
	'environment' => 's/^#?\s*LANG\s*=.*$/LANG=es_ES\@euro/;s/^#?\s*LC_MESSAGES\s*=.*$/LC_MESSAGES=es_ES\@euro/;s/^#?\s*LC_ALL\s*=.*$/LC_ALL=es_ES\@euro/;',
	'default/locale' => 's/^#?\s*LANG\s*=.*$/LANG=es_ES\@euro/;s/^#?\s*LC_MESSAGES\s*=.*$/LC_MESSAGES=es_ES\@euro/;s/^#?\s*LC_ALL\s*=.*$/LC_ALL=es_ES\@euro/;',
	'locale.alias' => 'if (/^es_ES\@euro/ ) { $anyade=0 }; print SALIDA "\n#Aadido por /usr/bin/eurocastellanizar\nes_ES\@euro         es_ES.ISO-8859-15\n# fin cambios\n" if (eof && $anyade)',
	'locale.gen' => 'if (/^es_ES/ ) { $anyade=0 }; if (/^#es_ES/) { $anyade=0; s/^#es_ES(.*)/es_ES$1/; }; print SALIDA "\n#Aadido por /usr/bin/eurocastellanizar\nes_ES ISO-8859-15\n# fin cambios\n" if (eof && $anyade)',
	'locale.nopurge' => 'if (/^es_ES/ ) { $anyade=0 }; if (/^#es_ES/) { $anyade=0; s/^#es_ES(.*)/es_ES$1/; }; print SALIDA "\n#Aadido por /usr/bin/eurocastellanizar\nes_ES\@euro\neu\neu_ES\neu_ES\@euro\n# fin cambios\n" if (eof && $anyade)',
	'profile' => 'if (/^# Aadido por \/usr\/bin\/eurocastellanizar/) {$anyade=0}; print SALIDA "\n# Aadido por /usr/bin/eurocastellanizar\nif [ -f /etc/language-euro-es ]; then source /etc/language-euro-es; fi\n# fin cambios\n" if (eof && $anyade)',
	'X11/XF86Config' => 's/^#?(\s*)XkbLayout(\s*)"(.*)"/$1XkbLayout$2"es"/;s/^#?(\s*)XkbKeymap(\s*)"xfree86(.*)"/$1XkbKeymap$2"xfree86(es)/',
	'X11/gdm/gdm.conf' => 's/^#?DefaultLocale=(.*)/DefaultLocale=es_ES\@euro/;s/^#?Welcome=(.*)/Welcome=Bienvenido a \%n/',
	'postgresql/postmaster.init' => 's/^#?\s*LANG=(.*)/LANG=spanish/',
	'texmf/language.dat' => 's/^%\s*spanish(.*)/spanish$1/',
        'inputrc' => 's/^#?\s*set\s*convert-meta(.*)/set convert-meta off/;s/^#?\s*set\s*output-meta(.*)/set output-meta on/;s/^#?\s*set\s*meta-flag(.*)/set meta-flag on/;',
        'Muttrc' => 's/^#?\s*set\s*locale="(.*)"/set locale="es"/;s/^#?\s*set\s*charset="(.*)"/set charset="iso-8859-15"/',
# Commented out due to bug #198444, even if it's a bug related to sysvinit
# I'm temporarily removing this until sysvinit fixes it.
#	'init.d/bootmisc.sh' => 's/echo \"System bootup in progress - please wait\"(.*)$/echo \"En proceso de arranque del sistema - por favor, espere\"$1/',
	'X11/xdm/Xresources' => 's/xlogin\*fail: Login incorrect/xlogin\*fail: Login fallido/',
	'X11/xdm/Xresources_0' => 's/xlogin\*fail: Login incorrect/xlogin\*fail: Login fallido/',
	'latex2html.config' => 's/^\$TITLES_LANGUAGE\s*=(.*)$/\$TITLES_LANGUAGE = "spanish"\;/; s/^\$default_language\s*=(.*)$/\$default_language = "spanish"\;/',
	'pine.conf' => 's/^#?character-set\s*=(.*)/character-set=ISO-8859-15/',
	'pgp.conf' => 's/^#?\s*Language\s*=\s*.*$/Language = es/;s/^#?\s*CharSet\s*=\s*.*$/CharSet = latin0/',
	'pgp-i.conf' => 's/^#?\s*Language\s*=\s*.*$/Language = es/;s/^#?\s*CharSet\s*=\s*.*$/CharSet = latin0/',
	'netscape4/defaults/preferences.js' => 's/^user_pref("intl.accept_languages", "(es)(.*)")\;/user_pref("intl.accept_languages", "es $2")\;s/user_pref("intl.font_charset", ".*")\;/user_pref("intl.font_charset", "iso-8859-15")\;/'

);

# Configure after changing
# First test if binary exists and if test is ok
# then run program.
$config_commands{'keymap'}{'bin'}  = '/usr/sbin/install-keymap';
$config_commands{'keymap'}{'test'} = '';
$config_commands{'keymap'}{'run'}  = '/usr/sbin/install-keymap /usr/share/keymaps/i386/qwerty/es.kmap.gz';
$config_commands{'locale'}{'bin'}  = '/usr/sbin/locale-gen';
$config_commands{'locale'}{'run'}  = '/usr/sbin/locale-gen';
$config_commands{'locale'}{'test'} = '';
# Is this ok??
#$config_commands{'localedef'}{'bin'} = '/usr/bin/localedef';
#$config_commands{'localedef'}{'run'} = "/usr/bin/localedef -i es_ES -f ISO-8859-1 es_Es";
#$config_commands{'localedef'}{'test'} = '/usr/share/locale/es_ES/';


# A HACER:
# 4.- /etc/console-tools/config
# SCREEN_FONT=lat0-16.psf
# 7.- /etc/Muttrc
# comentar unset use_from (para tener acentos)
# 8.- descomentar de /etc/locale.gen el locale es y ejecutar /usr/bin/locale-gen
# o localedef -i es_ES -f ISO-8859-1 spanish

# HECHO
# 1.- HECHO- Comprobar donde se pone la configuracion generica de netscape
# netscape/preferences.js:
# user_pref("intl.font_charset", "iso-8859-1");
# user_pref("intl.accept_languages", "Spanish/Spain [es-ES],Spanish [es],en");
# 2.- HECHO- tocar /etc/X11/XF86Config:   
# XkbLayout "xx" -> XkbLayout "es"
# XkbKeymap       "xfree86(us)" -> "xfree86(es)"
# 3.- HECHO  tocar /etc/X11/gdm/gdm.conf:
#  DefaultLocale=es_ES
#  Welcome=Bienvenido a %n
# 6.- HECHO postgresql/postmaster.init
# 7.- HECHO poner menus en castellano (traducidos menus en paquete menu)
# 8.- HECHO Poner en /etc/kbd el fichero es.kmap como default.kmap
# (llamar a install-keymap ??)
# 9.- HECHO nologin de /etc/init.d/bootmisc.sh

# Solo hace esto en versiones antiguas
create() if ! -e "/etc/default/locale" ;

print "Comprobando $config_dir\n" if !$opt_quiet;
foreach $file (keys(%ficheros_conf)) {
	patch($config_dir.$file,$ficheros_conf{$file}) if (!$only_checkfile  || $file eq $only_checkfile) ;
}


if ( $uid != 0 ) {         
	print STDERR "AVISO: No est ejecutando $0 como superusuario, es posible\n";
        print STDERR "que algunos de los comandos para cambiar el entorno no\n";        print STDERR "se ejecuten correctamente.\n";
}

# Now run commands as superuser to finish configuring the environment
foreach $cmd ( keys %config_commands ) {
	run_cmd($config_commands{$cmd}{'bin'},$config_commands{$cmd}{'test'},$config_commands{$cmd}{'run'});
}

exit 0;

sub run_cmd {
# Run commands, first test if binary exists and if precondition (test)
# works ok.
	local $binary = shift (@_);
	local $test = shift (@_);
	local $run = shift (@_);
	if ( -e $binary ) {
		if ( $test ne "" || -e $test ) {
			print "Ejecutando $binary.\n" if !$opt_quiet;
			exec($run);
		}
	} else {
		print "AVISO: No puedo encontrar $binary.\n" if !$opt_quiet;
	}

}

sub patch 
{
	local $file=shift (@_);
	local $regexp=shift (@_);
	local $anyade=1;
	# Abre un fichero, lo parchea con la expresin regular dada
	# y lo cierra
	if (!-e $file) {
		print "AVISO: No existe el fichero $file, no se adaptar.\n" if !$opt_quiet;
	# OJO que aqu en algunos casos a lo mejor interesa aadirlo
	# Por ejemplo: environment. La solucin adoptada ha sido
        # crearlos al principio (funcin create)
	}
	else {
		my $ok = 1;
		if ( $opt_pregunta ) {
			$ok = 0;
			print "Desea vd. que modifique el fichero $file (si/[no])? ";
			my $test = readline(*STDIN);
			$ok = 1 if $test =~ /si?/;

		}
		if ( $ok ) {
			print "Abriendo el fichero $file para adaptar al espaol.\n" if !$opt_quiet;
			rename ("$file","$file$prefix") || die ("No puedo mover $file a ".$file.$prefix.": $!");
			open (ENTRADA,"<$file$prefix") || die ("No puedo abrir $file$prefix: $!\n");
			open (SALIDA,">$file") || die ("No puedo abrir $file :$!\n");
			print "Se evaluar la expresin regular $regexp sobre el fichero\n" if $opt_debug;
			while ($origline=<ENTRADA>) 
			{
				$_=$origline;
				eval $regexp;
				$line=$_;
				if ( $opt_debug > 1 && $origline ne $line ) {
					$separator= "-"x50;
					print "Se modifica la linea\n$separator\n$origline$separator\npor\n$separator\n$line$separator\n";
				}
				print SALIDA;
			}
			close ENTRADA; close SALIDA;
		}
	}
	return 0;
}


sub create
{
# Crea los ficheros que pueden no existir y que conviene que
# s existan, de momento como slo es el /etc/environment
# lo creamos y punto, en un futuro se podran poner un hash
# array con el fichero y las lneas a aadir como se hace
# para la funcin patch 
	my $file=$config_dir."environment";
	my $contain="# Aadido automticamente por el programa 'eurocastellanizar'\nexport LANG=es_ES\@euro\nexport LC_MESSAGES=es_ES\@euro\nexport LC_ALL=es_ES\@euro\n# fin cambios\n";
	if ( !-e $file ){
		print "Creando el fichero $file\n" if !$opt_quiet;
		open (FILE,">$file") || die "No puedo crear el fichero $file\n: $!";
		print  FILE $contain;
		close FILE;
	}
	return 0;
}

