#!/bin/sh
#-*-tcl-*-
# the next line restarts using wish \
    exec wish "$0" -- ${1+"$@"}

#
# TkRev Main program -- A Tk interface to CVS.
#
# Uses a structured modules file -- see the manpage for more details.
#
# Author:  Del (del@babel.dialix.oz.au)
#

# If we can't get this far (maybe because X display connection refused)
# quit now.  If we get further, the error message is very misleading.
if {[info exists starkit::topdir]} {
  package require Tk
}

if {! [info exists tk_version] } {
  puts "Initialization failed"
  exit 1
}

if {$tk_version < 8.6} {
  puts "TkRev requires Tcl/Tk 8.6 or better!"
  exit 1
}

############################################################
# Find out how we're invoked, so we can find our libraries
############################################################
if {[info exists starkit::topdir]} {
  set TclRoot [file join $starkit::topdir lib]
  set ScriptBin $starkit::topdir
} else {
  if {[info exists TclRoot]} {
    # Perhaps we are being sourced recursively.
    # That would be bad.
    return
  }
  set Script [info script]
  set ScriptTail [file tail $Script]
  #puts "Tail $ScriptTail"
  if {[file type $Script] == "link"} {
    #puts "$Script is a link"
    set ScriptBin [file join [file dirname $Script] [file readlink $Script]]
  } else {
    set ScriptBin $Script
  }
  #puts "ScriptBin $ScriptBin"
  set TclRoot [file join [file dirname $ScriptBin]]
  #puts "TclRoot $TclRoot"
  if {$TclRoot == "."} {
    set TclRoot [pwd]
  }
  #puts "TclRoot $TclRoot"
  set TclRoot [file join [file dirname $TclRoot] "lib"]
  #puts "TclRoot $TclRoot"
  
  # allow runtime replacement
  if {[info exists env(TCLROOT)]} {
    set TclRoot $env(TCLROOT)
  }
  #puts "TclRoot $TclRoot"
}

set TclExe [info nameofexecutable]
if {$tcl_platform(platform) == "windows"} {
  set TclExe [file attributes $TclExe -shortname]
}

set TCDIR [file join $TclRoot tkrev]
set cvscfg(bitmapdir) [file join $TclRoot tkrev bitmaps]
#puts "TCDIR $TCDIR"
#puts "BITMAPDIR $cvscfg(bitmapdir)"

############################################################
# Now get some settings we need
############################################################
set cvscfg(version) "9.6.1"

if {! [info exists cvscfg(editorargs)]} {
  set cvscfg(editorargs) ""
}
set auto_path [linsert $auto_path 0 $TCDIR]
set cvscfg(allfiles) false
if {! [info exists cvscfg(startwindow)]} {
  set cvscfg(startwindow) "workdir"
}
set cvscfg(auto_tag) false
set cvscfg(econtrol) false
set cvscfg(use_cvseditor) false

set maxdirs 15
set dirlist ""
set totaldirs 0

# Orient ourselves
if { [info exists env(HOME)] } {
  set cvscfg(home) $env(HOME)
} else {
  if {$tk_version >= 9.0} {
    set cvscfg(home) [file home]
  } else {
    set cvscfg(home) "~"
  }
}
if { [info exists env(USER)] } {
  set cvscfg(user) $env(USER)
} elseif { [info exists env(USERNAME)] } {
  # Windows
  set cvscfg(user) $env(USERNAME)
} else {
  set cvscfg(user) ""
}
set cvscfg(cvsroot) ""
set cvscfg(svnroot) ""
set cvscfg(gitroot) ""

# Read in defaults
if {[file exists [file join $TCDIR tkrev_def.tcl]]} {
  source [file join $TCDIR tkrev_def.tcl]
}

set optfile [file join $cvscfg(home) .tkrev]
set old_optfile [file join $cvscfg(home) .tkcvs]
if {[file exists $old_optfile] && ![file exists $optfile]} {
  file copy $old_optfile $optfile
}
if {[file exists $optfile]} {
  catch {source $optfile}
}
set pickfile [file join $cvscfg(home) .tkrev-picklists]
if {[file exists $pickfile]} {
  picklist_load
}
if {! [info exist cvsglb(directory)]} {
  set cvsglb(directory) [pwd]
}
if {[info exists cvsglb(cvsroot)]} {
  set cvscfg(cvsroot) [lindex $cvsglb(cvsroot) 0]
}

# Can be overridden on command line 
set cvsglb(vcspref) $cvscfg(vcspref)

# Clear some variables
set cvsglb(commit_comment) ""
set cvsglb(cvs_version) ""

if {$cvscfg(use_cvseditor) && ![info exists cvscfg(terminal)]} {
  cvserror "cvscfg(terminal) is required if cvscfg(use_cvseditor) is set"
}

############################################################
# Detect platform windowing system and try to more or less match it
############################################################
colors:match_desktop

# Once we have a UI, initialize logging (classes are C,F,T,D)
if { ! [info exists cvscfg(log_classes)] } {
  set cvscfg(log_classes) "C"
}
foreach class [split $cvscfg(log_classes) {}] {
  set logclass($class) $class
}
if { ! [info exists cvscfg(logging)] } {
  set cvscfg(logging) false
}
load_all_images
if {$cvscfg(logging)} {
  gen_log:init
  # log the trace stuff we saved from before we could post it
  if {[regexp {[FD]} $cvscfg(log_classes)]} {
    gen_log:color $start_log
  }
}

############################################################
#
# Command line options
#
############################################################
set usage "Usage:"
append usage "\n tkrev \[--vcs <vcs precedence>\] \[--root <repository>\] \[--dir <starting directory>] \[--win workdir|module|merge\]"
append usage "\n tkrev \[--log|blame <file>\]"
append usage "\n tkrev <file> - same as tkrev --log <file>"
for {set i 0} {$i < [llength $argv]} {incr i} {
  set arg [lindex $argv $i]
  set val [lindex $argv [expr {$i+1}]]
  switch -regexp -- $arg {
    {^--*d.*} {
      # -ddir: Starting directory
      set dir $val; incr i
      cd $dir
    }
    {^--*v.*} {
      # -vcs: which version control system(s) to prefer. Will override cvscfg(vcspref)
      set colorglb(vcspref) $val; incr i
    }
    {^--*r.*} {
      # -root: CVSROOT, SVN URL, or Git origin
      set cvscfg(cvsroot) $val; incr i
    }
    {^--*w.*} {
      # workdir|module|merge: window to start with. workdir is default.
      set cvscfg(startwindow) $val; incr i
      lassign [vcs_detect [pwd]] incvs insvn inrcs ingit
    }
    {^--*l.*} {
      # -log <filename>: Browse the log of specified file
      set cvscfg(startwindow) log
      set lcfile $val; incr i
      lassign [vcs_detect [pwd]] incvs insvn inrcs ingit
    }
    {^--*[ab].*} {
      # annotate|blame: Browse colorcoded history of specified file
      set cvscfg(startwindow) blame
      set lcfile $val; incr i
      lassign [vcs_detect [pwd]] incvs insvn inrcs ingit
    }
    {^-psn_.*} {
      # Ignore the Carbon Process Serial Number, in case we're in a MacOS package
      incr i
    }
    {^--*h.*} {
      puts $usage
      exit 0
    }
    {^\.*\w*} {
      # If a filename is provided as an argument, assume -log
      # except if it's a directory and it's CVS or RCS, which don't
      # version directories. In that case, instead of throwing an error
      # let's just open the workdir in the arg directory
      lassign [vcs_detect [pwd]] incvs insvn inrcs ingit
      if {!($insvn || $ingit) && [file isdirectory $arg]} {
        set dir $arg
        cd $arg
      } else {
        set cvscfg(startwindow) log
        set lcfile $arg; incr i
      }
    }
    default {
      puts $usage
      exit 1
    }
  }
}

if {[info exists lcfile]} {
  set d [file dirname $lcfile]
  set f [file tail $lcfile]
  set lcfile $f
  cd $d
}

if {![info exists cvscfg(ignore_file_filter)]} {
  set cvscfg(ignore_file_filter) ""
}
if {[info exists cvscfg(file_filter)]} {
  unset cvscfg(file_filter)
}
if {![info exists cvscfg(show_file_filter)]} {
  set cvscfg(show_file_filter) "*"
}

set cvsglb(root) ""
set cvsglb(vcs) ""

# Create a window
# Start with Module Browser
if {[string match {mod*} $cvscfg(startwindow)]} {
  wm withdraw .
  # If we're in a version-controlled directory, open that repository
  if {$insvn} {
    set cvsglb(root) $cvscfg(svnroot)
    set cvsglb(vcs) svn
  } elseif {$incvs} {
    set cvsglb(root) $cvscfg(cvsroot)
    set cvsglb(vcs) cvs
  } elseif {$ingit} {
    set cvsglb(root) $cvscfg(url)
    set cvsglb(vcs) git
  } elseif {$inrcs} {
    set cvsglb(root) $cvscfg(rcsdir)
    set cvsglb(vcs) rcs
  } else {
    # We'll respect CVSROOT environment variable if it's set
    if {[info exists env(CVSROOT)]} {
      gen_log:log D "setting cvsglb(root) from CVSROOT envvar"
      set cvsglb(root) $env(CVSROOT)
      set cvscfg(cvsroot) $env(CVSROOT)
      set cvsglb(vcs) cvs
    }
  }
  # Othewise we set it to the most recent saved in picklist
  # which we've saved in cvscfg(cvsroot)
  if {$cvsglb(root) == ""} {
    gen_log:log D "setting cvsglb(root) to the last one visited"
    set cvsglb(root) $cvscfg(cvsroot)
  }
  modbrowse_run
  # Start with Branch Browser
} elseif {$cvscfg(startwindow) == "log"} {
  if {! [file exists $lcfile]} {
    puts "ERROR: $lcfile doesn't exist!"
    exit 1
  }
  wm withdraw .
  if {$incvs} {
    cvs_branches [list $lcfile]
  } elseif {$inrcs} {
    set cwd [pwd]
    set module_dir ""
    rcs_branches [list $lcfile]
  } elseif {$insvn} {
    svn_branches [list $lcfile]
  } elseif {$ingit} {
    git_branches [list $lcfile]
  } else {
    puts "File doesn't seem to be in CVS, SVN, RCS, or GIT"
  }
  # Start with Annotation Browser
} elseif {$cvscfg(startwindow) == "blame"} {
  if {! [file exists $lcfile]} {
    puts "ERROR: $lcfile doesn't exist!"
    exit 1
  }
  wm withdraw .
  if {$incvs} {
    cvs_annotate $current_tagname [list $lcfile]
  } elseif {$insvn} {
    svn_annotate rBASE [list $lcfile]
  } elseif {$ingit} {
    read_git_dir .
    git_annotate $current_tagname [list $lcfile]
  } else {
    puts "File doesn't seem to be in CVS, SVN, or GIT"
  }
  # Start with Directory Merge
} elseif {[string match {mer*} $cvscfg(startwindow)]} {
  wm withdraw .
  if {$incvs} {
    cvs_joincanvas
  } elseif {$insvn} {
    svn_directory_merge
  } else {
    puts "Directory doesn't seem to be in CVS or SVN"
  }
  # The usual way, with the Workdir Browser
} else {
  setup_dir
}

