#!/usr/bin/perl -w

use strict;

my @cmdnames;
my @cmdlevels;
my @cmdargs;
my @cmddesc;
my @cmdfunc;
my @protos;
my @files;

my @filelist = <*.c>;

my $modname;

unless (@ARGV) {
  print "Usage: $0 <module name>\n";
  exit(0);
} else {
  $modname=$ARGV[0];
}

for (@filelist) {
  next if (/commandlist.c/);
  
  my $fname = $_;
  my ($cn, $cl, $ca, $cd, $cf, $cp);

  open INFILE,"<$fname";
  
  while(<INFILE>) {
    chomp;
    
    if (/CMDNAME: (.*)/) {
      $cn=$1;
    }
        
    if (/CMDLEVEL: (.*)/) {
      $cl=$1;
    }
    
    if (/CMDARGS: (.*)/) {
      $ca=$1;
    }
    
    if (/CMDDESC: (.*)/) {
      $cd=$1;
    }
    
    if (/CMDFUNC: (.*)/) {
      $cf=$1;
    }
    
    if (/CMDPROTO: (.*)/) {
      $cp=$1;
    }
  }
  
  if (defined $cn and defined $cl and defined $ca and defined $cd and defined $cf and defined $cp) {
    # valid command found 
    push @files, $fname;
    push @cmdnames, $cn;
    push @cmdlevels, $cl;
    push @cmdargs, $ca;
    push @cmddesc, $cd;
    push @cmdfunc, $cf;
    push @protos, $cp;
  } else {
    print "Warning: found source file $fname without complete tags, skipping...\n";
  }
}

if (@files < 1) {
  print "No commands found - are you in the right directory?\n";
  print "Exiting before I destroy something important.\n";
  exit(0);
}


open CL, ">commandlist.c";

print CL "/* Automatically generated by mkcommandlist.pl, do not edit. */\n\n";
print CL "#include \"../chanserv.h\"\n\n";

# Print prototypes
print CL "/* Prototypes */\n";
foreach (@protos) {
  print CL "$_\n";
}

my @names2 = @cmdnames;
my @func2 = @cmdfunc;

print CL "\nvoid _init() {\n";

while (my $cn = shift @cmdnames) {
  print CL "  chanservaddcommand(\"".$cn."\", ".(shift @cmdlevels).", ".(shift @cmdargs).", ";
  print CL (shift @cmdfunc).", \"".(shift @cmddesc)."\");\n";
}

print CL "}\n\nvoid _fini() {\n";

while (my $cn = shift @names2) {
  print CL "  chanservremovecommand(\"".$cn."\", ".(shift @func2).");\n";
}

print CL "}\n";

close CL;

open MF,">Makefile";

print MF "# Automatically generated Makefile, do not edit.\n\n";

print MF ".PHONY: all Makefile\n";

print MF "all: Makefile $modname\n\n";

print MF "Makefile:\n";
print MF "\t../mkcommandlist.pl $modname\n";

print MF "\n$modname: ";

push @files,"commandlist.c";

foreach (@files) {
  s/.c$/.o/;
  print MF "$_ ";
}

print MF "\n";
print MF "\t ld -shared -Bdynamic -o \$\@ \$\^ \n";

close MF;
