#!/usr/bin/env tclsh
# KitCreator downloader v0.1.1 -- download Tclkits generated by
# http://kitcreator.rkeene.org/kitcreator. Works with Tcl 8.5+ and Jim Tcl.
# Copyright (C) 2016, dbohdan.
# License: MIT.
proc download url {
    set page [split [exec curl -s $url] \n]
    set descr [lsearch -glob -inline $page *Description:*]
    regexp {(http://kitcreator.rkeene.org/[^"]+/tclkit)} \
            [lsearch -glob -inline $page *URL:*] _ url

    set filename tclkit

    regexp {Tcl ([0-9.]+)} $descr _ version
    append filename -$version

    regexp {Platform ([-a-z0-9]+)} $descr _ platform
    append filename -$platform

    if {[regexp {packages statically linked} $descr]} {
        append filename -staticpkgs
    }

    if {[regexp {Threaded} $descr]} {
        append filename -threaded
    }

    if {[regexp {Packages: (.*)} $descr _ packages]} {
        foreach package $packages {
            set package [string trimright $package ,]
            append filename -$package
        }
    }

    puts "Downloading $url to $filename..."
    exec curl -o $filename $url >@ stdout 2>@ stderr
}

set url [lindex $argv 0]
if {$url eq {}} {
    puts "usage: $argv0 url"
    puts {The URL must be a KitCreator Web Interface build page.}
} else {
    download $url
}
