#! /opt/bin/wish

# user settable section

set BACKUP_HOME	$env(BACKUP_HOME)
set found 0
set configfiles "$BACKUP_HOME/lib/backup.conf /etc/buserver.conf /etc/afbackup/server.conf"
lappend configfiles "@serverlibdir@/@serverconf@"
foreach configfile "$configfiles" {
  if { [ file readable $configfile ] } {
    set found 1
    break
  }
}

if { ! $found } {
  puts stderr "Error: Cannot read configuration file. Exiting."
  exit 2
}

set textwidth	30
set entrywidth	35

set num_fix_params	24
set num_var_sp_idx	0

set comments(1) {\DEVICE SPECIFICATION\\The device name (No-Rewind-Version !)}
set comments(2) {\The blocksize of the device}
set comments(3) {\Flag, whether the device is a robot / cartridge handling system (0 or 1)}
set comments(4) {\Insert your number of cartridges, whether you have a robot or not}
set comments(5) {\The last cartridges of different cartridge sets, if requested.\Default is 1 set with cartridges ranging from 1 up to the\previous parameter. If e.g. 3 cartridge sets are requested:\1-3, 4-8, 9-10, supply here: 3 8 10\If not all cartridges should be used, the last number may be\smaller than the previous parameter}
set comments(6) {\The maximum number of bytes per file on tape}
set comments(7) {\Time to wait from the moment, a new cartridge has been inserted\ until a new action is attempted on the tape device}
set comments(8) {\Time to wait while the device is unavailable until a mail is\ sent to the user in charge}
set comments(9) {\Time to wait while the device is unavailable until abort}
set comments(10) {\The interval in seconds for probing, if device is ready, when\inserting another cartridge is requested. 0 for no probing.}
set comments(11) {\\SHELL-COMMANDS FOR TAPE HANDLING\\In these commands %d is replaced by the device name,\%n by the number, if within the command the count starts with 1,\%m by the number, if the count starts with 0.\\Command to set the file # on tape}
set comments(12) {\Command to skip to the next %n-th file on tape}
set comments(13) {\If there is a command to set the cartridge directly, supply it here}
set comments(14) {\If the cartridges can only by changed successively, insert the\command to change them here. This is also the command, that unloads\the tape, if you have no cartridge handler.}
set comments(15) {\The command to erase the tape. This is necessary on some systems.}
set comments(16) {\\CONFIGURATION FOR NON-EXISTING CARTRIDGE HANDLING SYSTEM\\The user to inform, if a cartridge should be changed manually}
set comments(17) {\\The mail-program to use.\\Insert %u for the position, where the username has to appear.}
set comments(18) {\\FILES TO SAVE THE STATE AND LOGGINGS\\Filename to save the actual tape position}
set comments(19) {\Filename for error loggings etc.}
set comments(20) {\Locking file to prevent several server starts}
set comments(21) {\The file with the authentication encryption key}
set comments(22) {\\CONFIGURATION FOR REMOTE_EXECUTION\\Directory, where remotely started programs must reside}
set comments(23) {\\SERVER-STARTUP AND SHUTDOWN ACTIONS\\shell-command to perform, when the server starts}
set comments(24) {\\shell-command to perform, when the server exits}

set names(1) {Backup-Device}
set names(2) {Tape-Blocksize}
set names(3) {Cartridge-Handler}
set names(4) {Number Of Cartridges}
set names(5) {Last Cartridges}
set names(6) {Max Bytes Per File}
set names(7) {Cart-Insert-Gracetime}
set names(8) {Device Unavail Send mail after min}
set names(9) {Device Unavail give up after min}
set names(10) {Device-Probe Interval}
set names(11) {SetFile-Command}
set names(12) {SkipFiles-Command}
set names(13) {Set-Cart-Command}
set names(14) {Change-Cart-Command}
set names(15) {Erase-Tape-Command}
set names(16) {User To Inform}
set names(17) {Mail-Program}
set names(18) {Tape-Pos-File}
set names(19) {Logging-file}
set names(20) {Lock-file}
set names(21) {Encryption-Key-File}
set names(22) {Program-Directory}
set names(23) {Init-Command}
set names(24) {Exit-Command}

set patterns(1) {[Bb]ackup[-_ \t]*[Dd]evi?c?e?:?}
set patterns(2) {[Tt]ape[-_ \t]*[Bb]lock[-_ \t]*[Ss]ize:?}
set patterns(3) {[Cc]artr?i?d?g?e?[-_ \t]*[Hh]andler:?}
set patterns(4) {[Nn]umb?e?r?[-_ \t]*[Oo]f[-_ \t]*[Cc]artr?i?d?g?e?s[-_ \t]*:?}
set patterns(5) {[Ll]ast[-_ \t]*[Cc]artr?i?d?g?e?s[-_ \t]*:?}
set patterns(6) {[Mm]axi?m?u?m?[-_ \t]*[Bb]ytes[-_ \t]*[Pp]er[-_ \t]*[Ff]ile:?}
set patterns(7) {[Cc]artr?i?d?g?e?[-_ \t]*[Ii]nse?r?t?[-_ \t]*[Gg]race[-_ \t]*[Tt]ime:?}
set patterns(8) {[Dd]evi?c?e?[-_ \t]*[Uu]n[Aa]vaila?b?l?e?[-_ \t]*[Ss]end[-_ \t]*[Mm]ail[-_ \t]*([Aa]fter[-_ \t]*)?[Mm]inu?t?e?s?:?}
set patterns(9) {[Dd]evi?c?e?[-_ \t]*[Uu]n[Aa]vaila?b?l?e?[-_ \t]*[Gg]ive[-_ \t]*[Uu]p[-_ \t]*([Aa]fter[-_ \t]*)?[Mm]inu?t?e?s?:?}
set patterns(10) {[Dd]evi?c?e?[-_ \t]*[Pp]rob(e|ing)[-_ \t]*[Ii]nterval:?}
set patterns(11) {[Ss]et[-_ \t]*[Ff]ile[-_ \t]*[Cc]o?mm?a?n?d:?}
set patterns(12) {[Ss]kip[-_ \t]*[Ff]iles?[-_ \t]*[Cc]o?mm?a?n?d:?}
set patterns(13) {[Ss]et[-_ \t]*[Cc]artr?i?d?g?e?[-_ \t]*[Cc]o?mm?a?n?d:?}
set patterns(14) {[Cc]hange[-_ \t]*[Cc]artr?i?d?g?e?[-_ \t]*[Cc]o?mm?a?n?d:?}
set patterns(15) {[Ee]rase[-_ \t]*[Tt]ape[-_ \t]*[Cc]o?mm?a?n?d:?}
set patterns(16) {[Uu]ser[-_ \t]*[Tt]o[-_ \t]*[Ii]nfor?m?:?}
set patterns(17) {[Mm]ail[-_ \t]*[Pp]rogram:?}
set patterns(18) {[Tt]ape[-_ \t]*[Pp]osi?t?i?o?n?[-_ \t]*[Ff]ile:?}
set patterns(19) {[Ll]ogg?i?n?g?[-_ \t]*[Ff]ile:?}
set patterns(20) {[Ll]ocki?n?g?[-_ \t]*[Ff]ile:?}
set patterns(21) {([Ee]n)?[Cc]rypti?o?n?[-_ \t]*[Kk]ey[-_ \t]*[Ff]ile:?}
set patterns(22) {[Pp]rogram[-_ \t][Dd]ire?c?t?o?r?y?:?}
set patterns(23) {[iI]niti?a?l?i?z?a?t?i?o?n?[-_ \t]*[Cc]o?mm?a?n?d:?}
set patterns(24) {[eE]xit[-_ \t]*[Cc]o?mm?a?n?d:?}

set prompts(1) {Streamer device (no-rewind):}
set prompts(2) {Device Blocksize:}
set prompts(3) {Cartridge handler:}
set prompts(4) {Number of cartridges:}
set prompts(5) {Last cartridges of sets:}
set prompts(6) {Max. number of bytes per file:}
set prompts(7) {Cartridge change gracetime:}
set prompts(8) {Device unav. send mail after:}
set prompts(9) {Device unavail. abort after:}
set prompts(10) {Device probing interval:}
set prompts(11) {Set-file-command:}
set prompts(12) {Skip-files-command:}
set prompts(13) {Set-cartridge-command:}
set prompts(14) {Change-cartridge-command:}
set prompts(15) {Erase-tape-command:}
set prompts(16) {User to inform:}
set prompts(17) {Mail program:}
set prompts(18) {Tape-position savefile:}
set prompts(19) {Logging-file:}
set prompts(20) {Lock-file:}
set prompts(21) {Encryption-Key-File:}
set prompts(22) {Program directory:}
set prompts(23) {Init command:}
set prompts(24) {Exit command:}

for { set i 1 } { $i <= $num_fix_params } { incr i } {
  set types($i) s
}
set types(3) b

set helps(1) "This is the device the backup is written to. It can be any
tape device with the capability to distinguish between several files on
the media. It is mandatory to supply the no-rewind device here.
Otherwise this package won't work properly. Suitable device
names for some OS-es:\\\\
AIX:\t\t/dev/rmt0.1\\
Solaris:\t\t/dev/rmt/0bn\\
IRIX:\t\t/dev/rmt/tps0d4nr\\
HP-UX:\t\t/dev/rmt/0hn\\
Linux:\t\t/dev/nst0\\
Digital UNIX:\t/dev/nrmt0h\\
Free BSD:\t/dev/nrst0"
set helps(2) "The blocksize of the tape device. This value specifies, how many
bytes are written to tape or read from it with one system call.
Usually this value is at least 512 or a multiple of it.
It is not very important if the blocksize is set to 2048
or 1024. The main thing to keep in mind is that if there is
a minimum, it should be respected (e.g. 1024 on AIX), otherwise
media space is wasted."
set helps(3) "This value must be 1 or 0, which means, that you either have a
cartridge handling system (i.e. some kind of robot) (1) or
not (0). If you don't have a robot, you may nonetheless maintain
a set of cartridges, that you have to manually number. The backup server
side will inform you via email or console output, whenever another
cartridge has to be inserted into the drive and what number it
requires it is."
set helps(4) "This number specifies, how many cartridges you are maintaining.
If you have a cartridge handling system (some kind of robot),
this must be the number of cartridges, your system is juggling."
set helps(5) "Several cartridge sets can be used. Here they may be specified
supplying the last cartridge of each set separated by whitespace.
If this parameter is not given, there is only the default set
number 1 with all available cartridges. Not all cartridges need
to be used by the sets, but only the last ones can be omitted.
E. g. if 3 cartridge sets are needed (1-3, 4-8, 9-10), you may
supply here: 3 8 10."
set helps(6) "The stream of data, that represents your backup, is divided into
pieces (files on tape). This is done to find the files faster
during a restore. This value determines, how large the pieces on
tape may be in bytes. Some good values for a few tape technologies:\\\\
  DAT:\t\t30000000\\
  Exabyte:\t50000000\\
  DLT:\t\t100000000"
set helps(7) "This is the time in seconds, the program waits after another
cartridge has been put into the drive. Normal devices need a
certain time span to mount the tape to get it ready for use.
Normally this value is not critical. If you estimate it too
low, the ioctl-system-call will wait until the
device becomes available. This time is sometimes longer than
two minutes, so if you want to proceed quickly after a cartridge
change, you may measure the maximum time, your system needs.
Some tried values for a few tape technologies:\\\\
  DAT:\t\t30\\
  Exabyte:\t70\\
  DLT:\t\t70"
set helps(8) "If the streaming device is not accessible (i.e. an open or a
tape handling command fails) or another backup server process
is still running, the server process re-tries his
attempts regularly. If it fails longer than the time in minutes
supplied here, an e-mail is sent to the configured user in
charge (see: User To Inform). Supplying 0 means: never send mail."
set helps(9) "If the streaming device is not accessible (i.e. an open or a
tape handling command fails), the server process re-tries his
attempts regularly. If it fails longer than the time in minutes
supplied here, it exits silently leaving a warning in the log file.
Supplying 0 means: try forever, never exit"
set helps(10) "This is the interval in seconds, after that regularly the device
is probed to be ready for reading. Thus after having ejected a
cartridge it is automatically recognized, if a new cartridge has
been inserted. For other media (e.g. exchangeable disks) this may
not be suitable. Supply a 0 in these cases for no probing."
set helps(11) "This is the (shell-) command to run to position the tape to a
certain file. Usually this is something like a combination
of: mt -f <device> rewind  and  mt -f <device> fsf <number>.
If the command you are supplying here starts to count with
1 for the first file on tape, you should insert %n for the
<number>. If it starts with 0, replace <number> with %m. If
you don't want to type the devicename again here, you may
write %d instead."
set helps(12) "This is the (shell-) command to run to skip over to a file
later on tape. Usually this is something like\\
mt -f <device> fsf <number>\\
Insert %n, where the number of files to skip over must be
supplied in the command, in the example instead of <number>,
and %d, where the device should appear (here: <device>)."
set helps(13) "This is the (shell-) command to run to put a certain
cartridge into the device. If the command you are supplying
here starts to count with 1 for the first cartridge, you
should insert %n in the place, where the cartridge number
must appear. If it starts with 0, replace it with %m. If
you don't want to type the devicename again here, you may
write %d instead. If you don't have a command to perform
this task, don't supply anything here. In this case you must set your
cartridge handling system to sequential mode (automatically
putting the next cartridge in, when the actual one is ejected)."
set helps(14) "This is the (shell-) command to run to eject a cartridge
actually placed inside the streamer device. This is normally
something like  mt -f <device> rewoffl  (but better consult
your man-pages). You have to supply this either if you have
no cartridge handling system (robot) or if you have no
command to set the cartridge directly by number. In the latter
case this package tries to maintain the number of the actual
cartridge in a file and to (hopefully) keep it consistent
with the reality. In this case the cartridge handling system
must be configured to sequential mode (automatically putting
the next cartridge in, when the actual one is ejected)."
set helps(15) "The (shell-) command to run, if the tape must be erased.
(actually not needed)."
set helps(16) "If you don't have a cartridge handling system (robot), a
human maintainer must put the appropriate cartridge into the
tape device. If you supply a mail program, an e-mail is sent
to the user given here, which informs him, that and which
cartridge (by number) must be put into the tape device.
If a timespan is configured, after that an automatic e-mail
should be sent due to an unaccessible tape device, it is
directed to this user."
set helps(17) "The mail program used to send messages to a human maintainer.
This is done, whenever another cartridge must be put into the
tape device and it can't be done automatically (by a robot or
whatever). If you don't want to type the username again here,
you can instead write %u . If you don't want mails to be sent,
you may instead supply any other command, that reads the standard
input and does something reasonable with it, e.g. redirects it
to the console:  cat > /dev/console"
set helps(18) "In this file some values are stored, e.g. the number of the
cartridge actually placed inside the streamer device."
set helps(19) "Logging information concerning errors or other notable events
is redirected to this file."
set helps(20) "To prevent the server program from being started several times
a lock file is created and this is it's name."
set helps(21) "The file containing the encryption key for authenticating
the backup client to the server. This file must contain
at least 5 characters and must not have read permission for
group or world."
set helps(22) "If you are using the remote start option for backing up
clients, this is the directory, where programs must reside,
that can be started remotely. No other programs can be
started remotely (for security reasons)."
set helps(23) "Here you may supply a (shell-) command to be run,
when the backup server side wakes up, i.e. the server process
starts. A %p appearing in this command is replaced with the name
of the client, that connected the backup service."
set helps(24) "Here you may supply a (shell-) command to be run,
when the backup server side goes to sleep, i.e. the server process
ends. A %p appearing in this command is replaced with the name
of the client, that connected the backup service."

# end of user settable section

set var_param_idx [ expr $num_fix_params + 2 ]
set fix_param_idx [ expr $num_fix_params + 1 ]

proc replSubstring { string to_repl replacement } {
  set new ""
  set repllen [ string length $to_repl ]

  while { $string != "" } {
    set idx [ string first $to_repl $string ]
    if { $idx >= 0 } {
      append new [ string range $string 0 [ expr $idx - 1 ] ]
      append new $replacement
      set string [ string range $string [ expr $idx + $repllen ] end ]
    } else {
      append new $string
      break
    }
  }

  return $new
}

proc getparam { pat } {
  global configfile

  set pattern {^[ \t]*}
  append pattern $pat
  append pattern {[ \t]*}


  set errfl [ catch { set fp [ open $configfile r ] } ]
  if { $errfl } {
    puts stderr "Error: cannot open $configfile."
    exit 0
  }

  while { [ gets $fp line ] >= 0 } {
    if { [ regexp -indices $pattern $line i1 ] } {
      close $fp
      set idx [ expr [ lindex $i1 1 ] + 1 ]
      return [ string trim [ string range $line $idx end ] ]
    }
  }

  close $fp
  return ""
}

for { set i 1 } { $i <= $num_fix_params } { incr i } {
  set values($i) [ getparam $patterns($i) ]
}
if { $num_var_sp_idx > 0 } {
  set num_var_params $values($num_var_sp_idx)
} else {
  set num_var_params 0
}
if { $num_var_params > 0 } {
  if { $num_var_params > 1 } {
    for { set i 0 } { $i < $num_var_params } { incr i } {
      set l [ expr $num_fix_params + $i + 1 ]
      set pattern [ replSubstring $patterns($var_param_idx) "#num#" [expr $i + 1] ]
      set values($l) [ getparam $pattern ]
    }
  } else {
    set values($fix_param_idx) [ getparam $patterns($fix_param_idx) ]
  }
}

proc what_now { } {
  tk_dialog .help "Help" "Make all the modifications in the entry fields on the right side you need after clicking once into the desired field. To get help on a specific item press F1 after clicking into the field." "" -1 Ok
}

proc show_win { } {
  global	num_fix_params values prompts num_var_sp_idx
  global	var_param_idx fix_param_idx types num_var_params
  global	textwidth entrywidth

  if { $num_var_sp_idx > 0 } {
    set num_var_params $values($num_var_sp_idx)
  } else {
    set num_var_params 0
  }

  catch { destroy .top }
  frame .top
  frame .top.mbar -relief raised -bd 2
  menubutton .top.mbar.help -text Help -underline 0 -menu .top.mbar.help.menu
  menu .top.mbar.help.menu
  .top.mbar.help.menu add command -label "What now" -command what_now -underline 0
  pack .top.mbar.help -side right
  pack .top.mbar -in .top -side top -fill x
  for { set i 1 } { $i <= $num_fix_params } { incr i } {
    frame .top.line$i
    label .top.line$i.label -width $textwidth -text $prompts($i)
    case $types($i) in {
      s {
	entry .top.line$i.value -width $entrywidth -textvariable values($i)
      }
      b {
	checkbutton .top.line$i.value -onvalue 1 -offvalue 0 -variable values($i)
      }
    }
    if { $i == $num_var_sp_idx } {
      bind .top.line$i.value <Return> show_win
    }
    bind .top.line$i.value <F1> "help_on $i"
    pack .top.line$i.label .top.line$i.value  -side left -fill x
    pack .top.line$i -in .top -side top -anchor w -fill x
  }

  if { $num_var_params > 0 } {
    if { $num_var_params > 1 } {
      for { set i 0 } { $i < $num_var_params } { incr i } {
        set l [ expr $num_fix_params + $i + 1 ]
	if { ! [ info exists values($l) ] } {
	  set values($l) ""
	}

        frame .top.line$l
        set prompt [ replSubstring $prompts($var_param_idx) "#num#" [expr $i + 1] ]
        label .top.line$l.label -width $textwidth -text $prompt
        case $types($var_param_idx) in {
          s {
	    entry .top.line$l.value -width $entrywidth -textvariable values($l)
          }
          b {
	    checkbutton .top.line$l.value -onvalue 1 -offvalue 0 -variable values($l)
          }
        }
        bind .top.line$l.value <F1> "help_on $l"
        pack .top.line$l.label .top.line$l.value  -side left -fill x
        pack .top.line$l -in .top -side top -anchor w -fill x
      }
    } else {
      frame .top.line$fix_param_idx
      label .top.line$fix_param_idx.label -width $textwidth -text $prompts($fix_param_idx)
      case $types($fix_param_idx) in {
        s {
	  entry .top.line$fix_param_idx.value -width $entrywidth -textvariable values($fix_param_idx)
        }
        b {
	  checkbutton .top.line$fix_param_idx.value -onvalue 1 -offvalue 0 -variable values($fix_param_idx)
        }
      }
      bind .top.line$fix_param_idx.value <F1> "help_on $fix_param_idx"
      pack .top.line$fix_param_idx.label .top.line$fix_param_idx.value  -side left -fill x
      pack .top.line$fix_param_idx -in .top -side top -anchor w -fill x
    }
  }

  frame .top.cmds
  button .top.cmds.save -text "Save" -command save_settings
  button .top.cmds.cancel -text "Exit" -command "exit 0"
  pack .top.cmds.save .top.cmds.cancel -side left
  pack .top.cmds -in .top -side top
  pack .top
}

proc save_settings { } {
  global	names values comments configfile num_var_sp_idx
  global	fix_param_idx var_param_idx num_fix_params num_var_params

  set errfl [ catch { set fp [ open $configfile w ] } ]

  if { $errfl } {
    tk_dialog .error "Error" "Error cannot open $configfile for writing." -1 Ok
    return
  }

  for { set i 1 } { $i <= $num_fix_params } { incr i } {
    set comment "# "
    append comment [ replSubstring $comments($i) "\\" "\n# " ]
    puts $fp $comment
    if { [ string length [ string trim $values($i) ] ] == 0 } {
      puts $fp "#$names($i):\t\t$values($i)"
    } else {
      puts $fp "$names($i):\t\t$values($i)"
    }
  }
  if { $num_var_params > 0 } {
    if { $num_var_params > 1 } {
      for { set i 0 } { $i < $num_var_params } { incr i } {
	set comment "# "
	append comment [ replSubstring $comments($var_param_idx) "\\" "\n# " ]
	set comment [ replSubstring $comment "#num#" [ expr $i + 1 ] ]
	set l [ expr $num_fix_params + 1 + $i ]
	puts $fp $comment
	set name [ replSubstring $names($var_param_idx) "#num#" [ expr $i + 1 ] ]
	if { [ string length [ string trim $values($l) ] ] == 0 } {
	  puts $fp "#${name}:\t\t$values($l)"
	} else {
	  puts $fp "${name}:\t\t$values($l)"
	}
      }
    } else {
      set comment "# "
      append comment [ replSubstring $comments($fix_param_idx) "\\" "\n# " ]
      puts $fp $comment
      if { [ string length [ string trim $values($fix_param_idx) ] ] == 0 } {
	puts $fp "#$names($fix_param_idx):\t\t$values($fix_param_idx)"
      } else {
	puts $fp "$names($fix_param_idx):\t\t$values($fix_param_idx)"
      }
    }
  }

  close $fp
}

proc help_on { idx } {
  global	helps num_fix_params var_param_idx values
  global	fix_param_idx num_var_sp_idx num_var_params

  if { $idx > $num_fix_params } {
    if { $num_var_params > 1 } {
      set num [ expr $idx - $var_param_idx + 2 ]
      set msg [ replSubstring $helps($var_param_idx) "#num#" $num ]
    } else {
      set msg $helps($fix_param_idx)
    }
  } else {
    set msg $helps($idx)
  }
  set msg [ replSubstring $msg "\n" " " ]
  set msg [ replSubstring $msg "\\" "\n" ]
  tk_dialog .help "Help" $msg "" -1 Ok
}

show_win

# Workaround for strange wish behaviour: window to small
update idletasks
set h [ winfo height .top.cmds.save ]
if { $h < 20 } {
  show_win
}
