#! /usr/bin/env tclsh

set teapotservers [list teapot.activestate.com]

lappend auto_path [file join [file dirname [info script]] lib]

package require teapotclient

proc print_help {} {
	puts stderr "Usage: teapot-client get <dir> <os> <cpu> <packages...>"
	puts stderr "Usage: teapot-client list ?<os> ?<cpu>??"
}

set cmd [lindex $argv 0]
set argv [lrange $argv 1 end]

switch -- $cmd {
	"get" {
		if {[llength $argv] < 4} {
			print_help
			exit 1
		}

		set dir [lindex $argv 0]
		set os [lindex $argv 1]
		set cpu [lindex $argv 2]
		set packages [lrange $argv 3 end]
		set extsinfo [::teapotclient::download_extensions $dir $teapotservers $packages $os $cpu]
		set exts [list]
		puts "Fetched Extensions:"
		foreach {ext extinfo} $extsinfo {
			lappend exts $ext
			puts "  $ext v[lindex $extinfo 0]"
		}

		set failedexts [list]
		foreach pkg $packages {
			if {[lsearch -exact $exts $pkg] == -1} {
				lappend failedexts $pkg
			}
		}
		if {[llength $failedexts] != 0} {
			puts "Failed to fetch:"
			foreach ext $failedexts {
				puts "  $ext"
			}
			exit 1
		}
	}
	"list" {
		set os [string tolower $tcl_platform(os)]
		set cpu [string tolower $tcl_platform(machine)]
		if {[llength $argv] > 0} {
			set os [lindex $argv 0]
		}
		if {[llength $argv] > 1} {
			set cpu [lindex $argv 1]
		}

		puts "Extensions available for OS=$os, CPU=$cpu:"

		array set exts [::teapotclient::get_extensions $teapotservers $os $cpu]
		foreach ext [lsort -dictionary [array names exts]] {
			set extinfo $exts($ext)

			set extvers [list]
			foreach extinfoitem $extinfo {
				set extinfoitemvers [lindex $extinfoitem 0]
				if {[lsearch -exact $extvers $extinfoitemvers] == -1} {
					lappend extvers $extinfoitemvers
				}
			}
			set extvers [lsort -decreasing -dictionary $extvers]

			puts "  $ext [lindex $extvers 0]"
		}
	}
	default {
		print_help
		exit 1
	}
}
