#!/bin/sh
# \
if [ `which tclkit`]; then exec tclkit "$0" -- "$@"; elif [ `which wish` ]; then exec wish "$0" -- "$@"; else echo "Please make sure tclkit or wish is in your PATH or run \"wish $0\""; exit; fi;

if {[info level] > 1} {return}

if {[catch {package require Tk 8.3}]} {
    puts stderr "Unable to locate Tk 8.3 or newer\nPlease make sure that Tk 8.3 or newer is installed and that [info nameofexecutable] is linked to the correct version"
    exit
}

set me [file dirname [info script]]

proc CreateWindow {} {
    global me
    set w .install
    toplevel $w -bd 1 -relief raised
    wm withdraw $w
    wm protocol $w WM_DELETE_WINDOW {exit}
    wm title .install "RoxIRC installation"
    
    frame $w.type -bd 2 -relief groove
    frame $w.type.t
    frame $w.type.b
    label $w.type.t.label -text "Install type"
    radiobutton $w.type.b.w -text "Site wide  " -variable installType -value w -command InstallType
    radiobutton $w.type.b.u -text "Single user" -variable installType -value u -command InstallType
    
    frame $w.rpath -bd 2 -relief groove
    label $w.rpath.label -text "RoxIRC install path"
    entry $w.rpath.entry
    
    frame $w.spath -bd 2 -relief groove
    label $w.spath.label -text "Scripts install path"
    entry $w.spath.entry
    
    frame $w.scripts -bd 2 -relief groove
    label $w.scripts.label -text "Install optional scripts"
    set s {}
    foreach x [glob -nocomplain [file join $me *]] {lappend s [file tail $x]}
    set s [replace $s prefs xresources config menus bindings startup help roxirc install CHANGES README]
    foreach x $s {checkbutton $w.scripts.$x -text $x -variable scripts($x)}

    frame $w.bottom
    button $w.bottom.ok -text "Install" -command {DoInstall}
    button $w.bottom.exit -text "Exit" -command {exit}
    
    pack $w.type -side top -fill both -padx 5 -pady 5 -ipadx 3 -ipady 3
    pack $w.type.t -side top -fill both
    pack $w.type.t.label -side top
    pack $w.type.b -side bottom -fill both
    pack $w.type.b.w -side top
    pack $w.type.b.u -side bottom
    
    pack $w.rpath -side top -fill both -padx 5 -pady 5 -ipadx 3 -ipady 3
    pack $w.rpath.label -side top -fill x -padx 3 -pady 3
    pack $w.rpath.entry -side top -fill x -padx 3 -pady 3
    
    pack $w.spath -side top -fill both -padx 5 -pady 5 -ipadx 3 -ipady 3
    pack $w.spath.label -side top -fill x -padx 3 -pady 3
    pack $w.spath.entry -side top -fill x -padx 3 -pady 3
    
    if {[set s [lsort [replace [winfo children $w.scripts] $w.scripts.label]]] != ""} {
        pack $w.scripts -side top -fill both -padx 5 -pady 5 -ipadx 3 -ipady 3
        grid $w.scripts.label -stick ew -padx 3 -pady 3 -columnspan 3
        foreach {x y z} $s {eval grid $x $y $z -sticky w -padx 3}
        grid columnconfigure $w.scripts {0 1 2} -weight 1
    }
    
    pack $w.bottom -side bottom -fill x -pady 5 -padx 5
    pack $w.bottom.ok -side right
    pack $w.bottom.exit -side left
    
    update idletasks
    wm geometry $w +[expr ([winfo screenwidth $w] / 2) - ([winfo reqwidth $w] / 2)]+[expr ([winfo screenheight $w] / 2) - ([winfo reqheight $w] / 2)]
    wm deiconify $w
}

proc InstallType {} {
    global tcl_platform env installType
    .install.rpath.entry delete 0 end
    .install.spath.entry delete 0 end
    if {$installType == "w"} {
        .install.rpath.entry insert 0 {/usr/local/bin}
        if {[string equal "FreeBSD" $tcl_platform(os)]} {
            .install.spath.entry insert 0 {/usr/local/share/doc/roxirc}
        } else {
            .install.spath.entry insert 0 {/usr/local/doc/roxirc}
        }
    } else {
        .install.rpath.entry insert 0 $env(HOME)/bin
        .install.spath.entry insert 0 $env(HOME)/.roxirc
    }
}

proc geterror {err} {
    return [join [lrange [split $err :] 1 end]]
}

proc DoInstall {} {
    global installType env scripts me
    if {[set rpath [.install.rpath.entry get]] == ""} {
        tk_dialog .dialog "Error" "You must specify a path to install the RoxIRC executable" error 0 OK
        return
    }
    if {[set spath [.install.spath.entry get]] == ""} {
        tk_dialog .dialog "Error" "You must specify a path to install the RoxIRC files" error 0 OK
        return
    }
    if {$installType == "u"} {
        if {$spath != "$env(HOME)/.roxirc"} {
            if {[tk_dialog .dialog "Warning" "RoxIRC looks for its files in ~/.roxirc\nIf you do not use this path you must always run RoxIRC with the -f option" warning 0 Change OK] == 0} {return}
        }
    } elseif {[lsearch {"/usr/local/share/doc/roxirc" "/usr/local/doc/roxirc" "/usr/local/roxirc"} $spath] == -1} {
        if {[tk_dialog .dialog "Warning" "The script dir\n\"$spath\"\nwill not be found automatically by RoxIRC\nYou will have to manually copy the files to your home directory" warning 0 Change OK] == 0} {return}
    }
    if {[lsearch [split [string trim $env(PATH) ()] ": "] $rpath] == -1} {
        if {[tk_dialog .dialog "Warning" "The directory\n\"$rpath\"\nis not in your PATH" warning 0 Change OK] == 0} {return}
    }
    if {![file isdir $spath] && [catch {file mkdir $spath} err]} {
        tk_dialog .dialog "Error" "Unable to create directory\n\"$spath\"\n[geterror $err]" error 0 OK
        return
    }
    if {![file isdir $rpath] && [catch {file mkdir $rpath} err]} {
        tk_dialog .dialog "Error" "Unable to create directory\n\"$rpath\"\n[geterror $err]" error 0 OK
        return
    }
    if {[catch {file copy -force [file join $me roxirc] $rpath} err]} {
        tk_dialog .dialog "Error" "Could not copy file\n\"[file join $me roxirc]\"\nto directory\n\"$rpath\"\n[geterror $err]" error 0 OK
        return
    }
    set files {prefs xresources config menus bindings startup help}
    foreach {s i} [array get scripts] {
        if {$i} {lappend files $s}
    }
    foreach x $files {
        if {[catch {file copy -force [file join $me $x] $spath} err]} {
            tk_dialog .dialog "Error" "Could not copy file\n\"[file join $me $x]\"\nto directory\n\"$spath\"\n[geterror $err]" error 0 OK
            return
        }
    }
    wm withdraw .install
    update idletasks
    tk_dialog .dialog "Installation Complete" "You should now edit \"[file join $spath config]\" to begin setting up RoxIRC\nThen run \"roxirc\" and see /set /color and /font for settings." {} 0 OK
    exit
}

proc replace {list args} {
    foreach x $args {
        if {[set i [lsearch $list $x]] > -1} {set list [lreplace $list $i $i]}
    }
    return $list
}

proc start {} {
    global env tcl_platform installType scripts
    wm withdraw .
    CreateWindow
    if {$tcl_platform(user) == "root"} {
        set installType w
    } else {
        set installType u
    }
    InstallType
    foreach x {single extras hilight} {
        if {[info exists scripts($x)]} {set scripts($x) 1}
    }
}

start
