#!/usr/bin/perl

use CGI;
use Mysql;
use Getopt::Long;

use Env qw(LSBUSER LSBDBPASSWD LSBDB LSBDBHOST);

sub usage()
{
print STDERR "mkcmdlist -v lsbversion\n";
die;
}

GetOptions("v=s" => \$lsbversion);
if( !$lsbversion ) { usage(); }

# Uncomment to trace SQL statments
#$trace=1;

#
# 2) Establish connection to the database
#

$Dbh = Mysql->connect($LSBDBHOST,$LSBDB,$LSBUSER, $LSBDBPASSWD) || die $Mysql::db_errstr;

#
# 3) Get the list of cmds
#

open(CMDS,">cmds.h");
print CMDS "/* Generated file */\n\n";
print CMDS "struct cmds {\n";
print CMDS "\tchar *cmdname;\n";
print CMDS "\tchar *cmdpath;\n";
print CMDS "};\nstruct cmds core_cmdlist[] = {\n";

# hack: move everything to core by taking out the
# qualifier on module ID=1 (see also next change)
$select = "SELECT DISTINCT Cid,Cname,Cpath FROM Command ";
$select.= "LEFT JOIN ModCmd ON MCcid=Cid ";
$select.= "WHERE (MCappearedin <= '$lsbversion' and MCappearedin<>'') ";
$select.= "AND (MCwithdrawnin IS NULL OR MCwithdrawnin > '$lsbversion') ";
#$select.= "AND Cbuiltin!='Yes' AND MCmid=1 ";
$select.= "AND Cbuiltin!='Yes' ";
$select.= "ORDER BY Cname ";

#print $select;

$sth = $Dbh->query($select) || die $Dbh->errmsg();

# hack: move everything to core by making the "desktop" module Id
# impossible to match (9999)
for(1..$sth->numrows) {
	%entry=$sth->fetchhash;
	print CMDS "	{\"$entry{'Cname'}\", \"$entry{'Cpath'}\"},\n";
}
print CMDS "};\n\nstruct cmds desktop_cmdlist[] = {\n";

$select = "SELECT DISTINCT Cid,Cname,Cpath FROM Command ";
$select.= "LEFT JOIN ModCmd ON MCcid=Cid "; 
$select.= "WHERE (MCappearedin <= '$lsbversion' and MCappearedin<>'') ";
$select.= "AND (MCwithdrawnin IS NULL OR MCwithdrawnin > '$lsbversion') ";
$select.= "AND Cbuiltin!='Yes' AND MCmid=9999 ";
$select.= "ORDER BY Cname ";

#print $select;

$sth = $Dbh->query($select) || die $Dbh->errmsg();

for(1..$sth->numrows) {
	%entry=$sth->fetchhash;
	print CMDS "	{\"$entry{'Cname'}\", \"$entry{'Cpath'}\"},\n";
}
print CMDS "};\n";

close(CMDS);
