#!/bin/sh
# ^-- little trick to restart using tclsh \
exec tclsh "$0" "$@"
if {$argc == 0} {
  puts "USAGE: greetinstall <eggdrop-configfile>"
  exit
  }
set cfgfile "[lindex $argv 0]"
if {![file exists $cfgfile]} {
  puts "ERROR: can't find $cfgfile."
  exit
  }
if {![file isfile $cfgfile]} {
  puts "ERROR: $cfgfile is no normal file."
  exit
  }
if {![file readable $cfgfile]} {
  puts "ERROR: can't read $cfgfile."
  exit
  }
if {![file writable $cfgfile]} {
  puts "ERROR: can't write $cfgfile."
  exit
  }
puts "Welcome to GreetWondeR Version 1.4 - INSTALLER"
set file [open $cfgfile r]
while {![eof $file]} {
  set line [gets $file]
  if {[string match "source *" $line]} {
    set scriptdir [lindex [split [lindex $line 1] /] 0]
    if {[string match "source *greetwonder*" $line]} {
      puts "\nAlready found an installed greetwonder.tcl: simply do a .rehash"
      puts "(make sure, that the new greetwonder.tcl is in ${scriptdir})\n"
      close $file
      exit
      }
    }
  lappend newcfgfile $line
  }  
close $file
set date [lrange [exec date] 0 2]
set time [lrange [exec date] 3 end]
if {![file exists $cfgfile.old]} {
  exec cp $cfgfile $cfgfile.old
  } {
  exec cp $cfgfile $cfgfile.old.[string trim $date " "]
  }
set file [open $cfgfile w]
foreach line $newcfgfile {
  puts $file $line
  }
puts $file "# This line was added by ./greetinstall on $date at $time"
puts $file "source ${scriptdir}/greetwonder.tcl"
close $file
puts "\nSuccessfully installed GreetWondeR.tcl. Now do a .rehash on the partyline."
puts "(Make sure, that the new greetwonder.tcl is in ${scriptdir})\n"
exit
