#!/usr/bin/wish -f
#
# GETTO source file
#  Copyright (C) 2005 Peter Salvi
#   Time-stamp: <2005.10.11., 10:26:54 (salvi)>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

##############################
## Creating the main window ##
##############################
wm title . "GETTO"
wm resizable . 0 0
frame .anime
listbox .anime.list -listvariable anime -selectmode extended \
    -state disabled -yscrollcommand { .anime.yscroll set } \
    -xscrollcommand { .xscroll set }
scrollbar .anime.yscroll -orient vertical -command { .anime.list yview }
scrollbar .xscroll -orient horizontal -command { .anime.list xview }
canvas .progress -height 15
set prfill [.progress create rectangle 0 0 0 15 -fill lightblue -state hidden]
label .status -textvariable statusbar
frame .buttons
button .buttons.check -text "Check" -command check
button .buttons.getto -text "Getto!" -command getto
pack .anime.list -in .anime -side left -expand true -fill both
pack .anime.yscroll -in .anime -side left -after .anime.list  -fill y
pack .buttons.check .buttons.getto -side left -in .buttons -expand true -fill x
pack .anime .xscroll .progress .status .buttons -fill x

########################
## Binding keystrokes ##
########################
bind . q exit
bind . c {.buttons.check invoke}
bind . g {.buttons.getto invoke}

####################################
## Reading the configuration file ##
####################################
set f [open "getto.conf"]
set num 0
# Setting the download path
gets $f s
while {![eof $f] && ([string first \# $s] == 0 || [string length $s] == 0)} {
    gets $f s
}
set path $s
# Reading the anime list
while {![eof $f]} {
    gets $f s
    if {[string first \# $s] == 0 || [string length $s] == 0} continue
    set i [string first " " $s]
    set j [string first " " $s [expr $i+1]]
    set config(title$num) [string range $s 0 [expr $i-1]]
    set config(site$num) [string range $s [expr $i+1] [expr $j-1]]
    set config(latest$num) [string range $s [expr $j+1] end]
    lappend anime "$config(title$num)($config(latest$num))"
    incr num
}

############################
## Checking for new anime ##
############################
proc check {} {
    global anime animeid config newepisode num prfill statusbar torrents

    set anime {}

    for {set i 0} {$i < $num} {incr i} {
        set tmp [.progress create rectangle 0 0 [expr $i.0 / $num.0 * \
                             [winfo width .progress]] 15 -fill lightblue]
        .progress delete $prfill
        set prfill $tmp
        set statusbar "Searching for $config(title$i)..."
        update idletasks

        if {[catch { set page [exec -- wget -q -t 3 --connect-timeout=10 \
                                   -O - $config(site$i)] }]} {
            tk_messageBox -icon warning -title "Page not found!" \
                -message "Cannot load the site: $config(site$i)" -type ok
            update
            continue
        }
        set j [expr $config(latest$i)+1]
        set found true

        while {$found} {
            set found false
            set matches [regexp -all -inline -line -nocase \
                             -- "^.*$config(title$i).*$j.*$" $page]
            for {set k 0} {$k < [llength $matches]} {incr k} {
                set title [regexp -inline -nocase \
                               -- {>[^>]*</a>} [lindex $matches $k]]
                set title [string range [lindex $title 0] 1 end-4]
                set torrent [regexp -inline -nocase \
                                 -- {href=.*torrent} [lindex $matches $k]]
                set torrent [string range [lindex $torrent 0] 6 end]
                set newitem "$config(title$i)($config(latest$i)): $title"
                if {[regexp -nocase -- "$config(title$i).*$j" $title] &&
                            [lsearch -exact $anime $newitem] == -1} {
                    set animeid([llength $anime]) $i
                    set newepisode([llength $anime]) $j
                    set torrents([llength $anime]) $torrent
                    lappend anime $newitem
                    set found true
                }
            }
            incr j
        }
    }

    set statusbar "Done."
    .progress itemconfigure $prfill -state hidden
    .anime.list configure -state normal
}

###############################
## Get the selected torrents ##
###############################
proc getto {} {
    global animeid config newepisode path torrents

    set selected [.anime.list curselection]
    foreach i $selected {
        set fname $torrents($i)
        # Local address
        if {![string equal [string range $fname 0 3] "http"] &&
            !([string first "/" $fname] == 0)} {
            set root $config(site$animeid($i))
            set root [string range $root 0 [string last "/" $root]]
            set fname $root$fname
        }
        # Absolute address, without server name
        if {[string first "/" $fname] == 0} {
            set root $config(site$animeid($i))
            set root [string range $root 0 [expr [string first "/" $root 7]-1]]
            set fname $root$fname
        }
        set cmd "wget -q -P $path \"$fname\""
        exec /bin/sh -c $cmd

        if {[expr $config(latest$animeid($i)) < $newepisode($i)]} {
            set cmd "cat getto.conf | sed \'s/\\(^$config(title$animeid($i)).*\\)$config(latest$animeid($i))/\\1$newepisode($i)/\' > getto.conf.new"
            exec /bin/sh -c $cmd
            exec /bin/sh -c "mv getto.conf.new getto.conf"
        }
    }
}