#!/usr/bin/tclsh

###   XkbBr ver 0.5 por iga, novembro de 1998   ###

## Help na linha de comando ##
if {$argc == 0} {
  puts stdout "XkbBr ver0.5 (novembro de 1998)\nUtilitrio para a configurao de teclado em portugus.\n\nMode de usar: xkbbr \"teclado\"\nTeclado: pc101: Teclado americano padro\n         abnt2: Teclado ABNT2 brasleiro\n"
  exit
} 

## Localizar o arquivo XF86Config e definir o nome do Back-up ##
set tmp [lsort -decreasing [exec find /etc -name XF86Config -print]]
if {[llength $tmp] > "1"} {
  puts stdout "Existe mais de um arquivo XF86Config."
  exit
}
if {[llength $tmp] == "0"} {
  puts stdout "Nao existe o arquivo XF86Config."
  exit 
}
set ArquivoConfig [lindex $tmp [lsearch -regexp $tmp {^/etc.+\XF86Config$}]]
set ArquivoBK $ArquivoConfig
append ArquivoBK ".xkbbr"

## Configurar as linhas do XF86Config referente ao teclado ##
if {$argv == "pc101"} {
    set NovoProtocol {    Protocol        "Standard"}
    set NovoRules    {    XkbRules        "xfree86"}
    set NovoModel    {    XkbModel        "pc101"}
    set NovoLayout   {    XkbLayout       "us_intl"}
} elseif {$argv == "abnt2"} {
    set NovoProtocol {    Protocol        "Standard"}
    set NovoRules    {    XkbRules        "xfree86"}
    set NovoModel    {    XkbModel        "abnt2"}
    set NovoLayout   {    XkbLayout       "br"}
} else {
  puts stdout "\nTeclado no suportado. Atualmente, o XkbBr suporta apenas pc101 e abnt2.\n"
  exit
}

## L o arquivo XF86Config ##
set XFConfig ""
set f [open $ArquivoConfig]
while {[gets $f linha] >= 0} {
  lappend XFConfig $linha
}
close $f

## Substitui as linhas correspondestes ao teclado ##
set inicio [lsearch $XFConfig {Section "Keyboard"}]
set fim $inicio
while {[lrange $XFConfig $fim $fim] != "EndSection"} {
  incr fim 1
}
incr inicio 1
incr fim -1
set NovoConfig [lreplace $XFConfig $inicio $fim $NovoProtocol $NovoRules $NovoModel $NovoLayout]

## Escreve o arquivo XF86Config ##
if {[catch {eval [exec cp $ArquivoConfig $ArquivoBK]}]} {
    puts stdout "Arquivo $ArquivoConfig no pode ser aberto."
    puts stdout "Verifique a permisso."
    exit
}
set f [open $ArquivoConfig w]
set linha 0
while {$linha < [llength $NovoConfig]} {
  puts $f [lindex $NovoConfig $linha]
  incr linha 1
}
close $f

puts stdout "\nXF86Config configurado para teclado $argv"
puts stdout "\nNo se esquea de mudar os locales. Coloque no seu ~/.bash_profile as linhas:\nLANG=pt_BR\nLC_ALL=pt_BR\nLC_CTYPE=ISO-8859-1\nLESSCHARSET=latin1\nexport LANG LC_ALL LC_CTYPE LESSCHARSET"

# eof
