# update.tcl v1.3
# Script to check for Blocktrix Updates

describe "Checks the internet for Blocktrix updates."

source scripts/http.tcl

set update(url) "http://update.blocktrix.org/"

if {![file exists "update.txt"]} { close [open "update.txt" w] }

proc update:check {{manual 0}} {
  global update
#  plinelog "Checking For Updates ..."
  if {[catch {http::geturl $update(url)} sock]} { return }
  set data [http::data $sock]
  set headers [http::header $sock]
  catch {http::Finish $sock}
  if {[string match "*ocation*" $headers]} {
    regexp {ocation: ([^ \n]*)} $headers - url
    if {[catch {http::geturl $url} sock]} { return }
    set data [http::data $sock]
    catch {http::Finish $sock}
  }
  if {[string match "*The document has moved*" $data]} {
    regexp {has moved <a href=\"([^\"]*)\"} [string tolower $data] - url
    if {[catch {http::geturl $url} sock]} { return }
    set data [http::data $sock]
    catch {http::Finish $sock}
  }
  set newvers [lindex [split $data \n] 0]
  set notes [lrange [split $data \n] 1 end]
  set infile [open "update.txt" r]
  set buffer [read $infile]
  close $infile
  set onewvers [lindex [split $buffer \n] 0]
  if {($newvers != [version]) && ($newvers != $onewvers)} {
    addtab "@ Update"
    foreach line $notes {
      tablog "@ Update" "$line"
    }
    tab "@ Update"
  }
  if {($newvers != [version]) && (($newvers != $onewvers) || ($manual))} {
    set answer [tk_messageBox -message "There is a new version of Blocktrix available.  Do you wish to download now?" -type yesno -icon question]
    if {$answer == "yes"} { upgrade }
  }
  set outf [open "update.txt" w]
  puts $outf "$newvers"
  puts $outf "[join $notes \n]"
  close $outf
}

addmenuitem "Check For Updates" {update:check 1}

if {[expr {[clock seconds] - [file mtime "update.txt"]}] >= 864000} { after 2000 update:check }

plinelog "update.tcl v1.3 by strikelight now loaded"

