#! /bin/sh
# $PostgreSQL: pgsql/src/pl/tcl/modules/pltcl_delmod.in,v 1.3 2006/03/11 04:38:40 momjian Exp $
#
# Start tclsh \
exec /c/Tcl/bin/tclsh "$0" "$@"

#
# Code still has to be documented
#

#load /usr/local/pgsql/lib/libpgtcl.so
package require Pgtcl


#
# Check for minimum arguments
#
if {$argc < 1} {
    puts stderr ""
    puts stderr "usage: pltcl_delmod dbname \[options\] modulename \[...\]"
    puts stderr ""
    puts stderr "options:"
    puts stderr "    -host hostname"
    puts stderr "    -port portnumber"
    puts stderr ""
    exit 1
}

#
# Remember database name and initialize options
#
set dbname [lindex $argv 0]
set options ""
set errors 0
set opt ""
set val ""

set i 1
while {$i < $argc} {
    if {[string compare [string index [lindex $argv $i] 0] "-"] != 0} {
        break;
    }

    set opt [lindex $argv $i]
    incr i
    if {$i >= $argc} {
        puts stderr "no value given for option $opt"
	incr errors
	continue
    }
    set val [lindex $argv $i]
    incr i

    switch -- $opt {
        -host {
	    append options "-host \"$val\" "
	}
	-port {
	    append options "-port $val "
	}
	default {
	    puts stderr "unknown option '$opt'"
	    incr errors
	}
    }
}

#
# Final syntax check
#
if {$i >= $argc || $errors > 0} {
    puts stderr ""
    puts stderr "usage: pltcl_delmod dbname \[options\] modulename \[...\]"
    puts stderr ""
    puts stderr "options:"
    puts stderr "    -host hostname"
    puts stderr "    -port portnumber"
    puts stderr ""
    exit 1
}

proc delmodule {conn modname} {
    set xname $modname
    regsub -all {\\} $xname {\\} xname
    regsub -all {'}  $xname {''} xname

    set found 0
    pg_select $conn "select * from pltcl_modules where modname = '$xname'" \
    MOD {
        set found 1
	break;
    }

    if {!$found} {
        puts "Module $modname not found in pltcl_modules"
	puts ""
	return
    }

    pg_result \
        [pg_exec $conn "delete from pltcl_modules where modname = '$xname'"] \
	-clear
    pg_result \
        [pg_exec $conn "delete from pltcl_modfuncs where modname = '$xname'"] \
	-clear

    puts "Module $modname removed"
}

set conn [eval pg_connect $dbname $options]

while {$i < $argc} {
    delmodule $conn [lindex $argv $i]
    incr i
}

pg_disconnect $conn
