#!/usr/bin/tclsh

#-----------------#
# Security        #
#-----------------#
catch { exec rm -rf /tmp/.sax_dir }
set make_dir [ catch {eval {exec mkdir /tmp/.sax_dir} } ]
if { $make_dir != 0 } {
 puts "Error: temporary directory still exists! Aborting for security \
              reasons."
 exit -1
}

proc ProveOnRoot  {} {
####---ProveOnRoot---#####
# this function proves if we are root
#
#-----------------#
# Prove on root   #
#-----------------#
set ID "nonroot"
catch { eval { exec whoami > /tmp/.sax_dir/user } }
set handle [ open "/tmp/.sax_dir/user" "r" ]
gets $handle ID
close $handle
catch { eval { exec rm -f /tmp/.sax_dir/user } }
if { $ID != "root" } {
  puts "Sorry: only root can do this"
  catch { exec rm -rf /tmp/.sax_dir }
  exit -1
}
}

proc GetRealName {server} {
###---GetRealName---####
# search for real server file 
# name
#
global var 
set server [ string toupper $server ]
cd $var(Xpath)
foreach s [lsort [glob X*]] {
 if { [file isfile $s] } {
  set UpName [ string toupper $s ]
  if { [ regexp -- "\(.*\)$server\(.*\)" $UpName ] == 1 } {
   set  RealServer $s
   return $RealServer
  }
 }
}
return "-1"
}

proc init {} {
#####--init--#########
# initalizes all data
#
#--------------#
# variables    #
#--------------#
global var
set var(ScanPci)   "/usr/X11R6/bin/scanpci"
set var(IdentFile) "/var/X11R6/sax/config/Identity"
set var(Xpath)     "/usr/X11R6/bin/"
}

proc GetOptions {iOptionList} {
###---GetOptions---######
# this function read all options
#
    upvar $iOptionList option
    global argv    
    set    argcount     "0"
    set    arg          ""
    set    option(-d)   ""

    while { 1 } {

        set arg [ lindex $argv $argcount ]
        incr argcount
        switch -glob -- "$arg" {

            -d             -
            --debug       {
                set arg "-d"
            }

            -*           {

                puts "error: '$arg' is not a valid option."
                catch { exec rm -rf /tmp/.sax_dir }
                exit -1
            }

            default          { break }
        }

        #--Save the content of the Option in option

        set option($arg) [ lindex $argv $argcount ]
        incr argcount

        if { $option($arg) == "" } {
            puts "error: missing parameter to option '$arg'!"
            catch { exec rm -rf /tmp/.sax_dir }
            exit -1
        }
    }
}

proc GetFields {filename listi keywords} {
#####---GetFields---######
# This Functions returns a list of fields 
# concerning to a file < filename >
#
upvar $listi erglist
set buffer    ""
set dummy     ""
set list      ""
set nr        0
set key       ""
set value     ""

#
# Initialize
#
foreach i $keywords {
  set data($i) ""
}

#
# Open the File < filename >
#
if { [ file exists $filename ]== 0 } {
 puts "file not found: $filename"
 catch { exec rm -rf /tmp/.sax_dir }
 exit -1
}

set handle [ open "$filename" "r"]

#
# While not end of file read
# lines into buffer
#
while { [ eof $handle ] == 0 } {

 gets $handle buffer
 #set buffer [ string toupper $buffer ] 
 if { [ string length $buffer ] == 0 } { continue }
 set buffer [ string trim $buffer ]
 if { [ string index $buffer 0 ] == "#" } {
  continue
 }

 #puts $buffer

 while { 1 } {

  if { [ regexp -- {(.*)\(.*)} $buffer dummy buffer part ] == 0 } {
     set buffer [ string trim $buffer ]          
     regexp -- {(.*)\=(.*)} $buffer dummy key value
     set key [ string trim $key ]
     set value [ string trim $value ]
     set data($key) $value
     break          
  }
 set part [ string trim $part ]
 if { [ string match {SEE*} $part ] == 0 } {
    regexp -- {(.*)\=(.*)} $part dummy key value
    set key [ string trim $key ]
    set value [ string trim $value ]
    set data($key) $value
 } else {
    set key SEE
    set value $part
    set data($key) $value
   } 
 }

  foreach i $keywords {
   set list [ linsert $list end $data($i) ]
   set data($i) ""
  }

 set erglist($nr) $list
 incr nr
 set list ""
}
close $handle
}

proc PciRead { iVendorId iDeviceId } {
####---PciRead---#####
# this function extract the information 
# from the scanpci output
#
set line ""
upvar $iVendorId VendorId
upvar $iDeviceId DeviceId
set DeviceId ""
set VendorId ""
set OutPut   ""
global var

catch {set OutPut [ exec $var(ScanPci) |& \
        cut --only-delimited -f2 -d: | grep -i vendor ] }

set ident "none"
foreach i $OutPut {
 set id [ string tolower $i ]
 set id [ string trim $id ]
 switch $id {
   "vendor" { 
     set ident "vendor"
     continue 
   }

   "device"   { 
     set ident "name"
     continue 
   }
 }

 if { $ident == "vendor" } {
  set VendorId [ linsert $VendorId end $i ]
 }
 if { $ident == "name" } {
  set DeviceId [ linsert $DeviceId end $i ]
 }
}
#puts $DeviceId
#puts $VendorId
}

#----------------#
# Main body      #
#----------------#
# do the task
#
ProveOnRoot
init
global OptionList
GetOptions OptionList


#
# first scan pci bus
#
set device    ""
set vendor    ""
PciRead vendor device 
#puts $vendor
#puts $device

#
# read keylist from pci file
#
global PciList
global var
set KeyWords {VID DID SERVER}
GetFields $var(IdentFile) PciList $KeyWords


#
# Create server list by 
# checking all IDs
#
global var
set server     ""
set ServerList ""
foreach i [ array names PciList ] {
 set vid [ lindex $PciList($i) 0 ]
 set vid [ string tolower $vid ]
 set did [ lindex $PciList($i) 1 ]
 set did [ string tolower $did ]
 if { ($did == "") || ($vid == "") } {
  continue
 }
 foreach v $vendor {
  if { $v == $vid } {
   foreach d $device {
    if { $d == $did } {
     set server [ lindex $PciList($i) 2 ]
     set server [ string toupper $server ] 
     set ServerList [ linsert $ServerList end $server ]
    }
   }
  }
 }
}

#
# make a uniq server list
#
set ServerList [ lsort $ServerList ]
set last    ""
set tmplist ""
foreach i $ServerList {
 if { $i != $last } {
   set tmplist [ linsert $tmplist end $i ]
 }
 set last $i
}
set ServerList $tmplist

#
# check on more than one element in 
# the list
#
set elements [ llength $ServerList ]
switch $elements {

 "1" {
  set RealName ""
  set RealName [ GetRealName $ServerList ]
 }

 default {
  foreach i $ServerList {
   if { $i == "SVGA" } {
    set ServerList $i
    set RealName ""
    set RealName [ GetRealName $ServerList ]
    break
   } else {
    set ServerList ""
    set RealName   ""
   }
  }
 }

}

#
# give me the result 
#
switch $OptionList(-d) {

 "yast"  {
  if { $ServerList == "" } {
   puts "Failed"
   catch { exec rm -rf /tmp/.sax_dir }
   exit 1
  } else {
   puts $ServerList
   if { $RealName == "-1" } { 
    catch { exec rm -rf /tmp/.sax_dir }
    exit 2 
   }
   catch { exec rm -rf /tmp/.sax_dir }
   exit 0
  } 
 }

 "sax"  {
  if { $ServerList == "" } {
   puts "Failed"
   catch { exec rm -rf /tmp/.sax_dir }
   exit 0
  } else {
   puts $ServerList
   if { $RealName == "-1" } {
    catch { exec rm -rf /tmp/.sax_dir }
    exit 0
   }
   catch { exec rm -rf /tmp/.sax_dir }
   exit 0
  }
 }

 default {
  if { $ServerList == "" } {
   puts "Failed"
   catch { exec rm -rf /tmp/.sax_dir }
   exit 0
  } else {
   if { $RealName != "-1" } {
    puts $RealName
    catch { exec rm -rf /tmp/.sax_dir }
    exit 0
   }
   puts "Failed"
   catch { exec rm -rf /tmp/.sax_dir } 
   exit 0
  }
 }

}
