#!/bin/sh  
# \
exec tclsh "$0" "$@"

proc APSStrictParseArguments {optlist} {
    upvar args arguments
    set length [llength $arguments]
    set index 0
    set leftovers {}
    while {$index<$length} {
        set arg [lindex $arguments $index]
        if {[string index $arg 0]=="-"} {
            set keywordName [string range $arg 1 end]
            if {[lsearch -exact $optlist $keywordName]!=-1} {
                incr index
                if {$index==$length} {
                    lappend leftovers $arg
                } else {
                    set valueString [lindex $arguments $index]
                    uplevel "set $keywordName {$valueString}"
                    incr index
                }
            } else {
                incr index
                lappend leftovers $arg
            }
        } else {
            lappend leftovers $arg
            incr index
        }
    }
    set arguments [concat $leftovers]
    if {$arguments != ""} {
        set procName [lindex [info level [expr {[info level] - 1}]] 0]
        puts stderr "Unknown option(s) given to $procName \"$arguments\""
        return -1
    } else {
        return 0
    }
}

set usage {usage: installExtensions -location <dirname> [-extensionList <list>]}
set location ""
set extensionList ""
set args $argv
if {[APSStrictParseArguments {location extensionList}] || ![string length $location]} {
	return -code error "$usage"
}
if {![file exists $location] || ![file isdir $location]} {
    return -code error "not found or not directory: $location"
}
if ![string length $extensionList] {
    set extensionList [list ca os rpn sdds]
}
foreach extension $extensionList {
    if ![file exists $extension/pkgIndex.tcl] {
        puts stderr "not found: $extension/pkgIndex.tcl"
        continue
    }
    if {$env(EPICS_HOST_ARCH) == "darwin-x86"} {
	if ![llength [set libList [glob -nocomplain $extension/O.$env(EPICS_HOST_ARCH)/*.dylib]]] {
	    puts stderr "no library found for $extension"
	    continue
	}
    } else {
	if ![llength [set libList [glob -nocomplain $extension/O.$env(EPICS_HOST_ARCH)/*.so]]] {
	    puts stderr "no library found for $extension"
	    continue
	}
    }
    catch {file mkdir $location/$extension}
    file copy -force $extension/pkgIndex.tcl $location/$extension
    eval file copy -force $libList $location/$extension
    puts stderr "Installed $extension"
}

