#!/usr/bin/perl
# buildlib.pl for IMP
#
local( %FILE_COMMENTS );
local( %FILE_NEEDED );
local( @INIT_ORDER );
local( $inc, $def, $func, $obj, $init );

$inc  = 'includes/';
$def  = 'defines/';
$func = 'functions/';
$obj  = 'objects/';
$init = 'initialization/';

$VALID_OPT = 0;

# Init all of the files as not-needed
init_needs_file();

# Database configuration stuff

# Dummy driver is used if none other is specified
#$NEED_V1_DBDUMMY   = 1;
#$NEED_V2_DBDUMMY   = 1;

# Flags to turn on / off database options
$NEED_MYSQL        = 0;             # Mysql database
$NEED_INFORMIX     = 0;             # Informix database
$NEED_ORACLE       = 0;             # Oracle database
$NEED_POSTGRES     = 0;             # Postgres database

$NEED_V1_DB        = 0;             # Version 1 of the database
$NEED_V2_DB        = 0;             # Version 2 of the database

#
$TARGET_DIR        = '../';
$NEED_USAGE        = 0;
$NEED_SESSION      = 0;

for( $i = 0; $i <= $#ARGV; $i++ ) {

    # Database options
   if ( valid_arg( $ARGV[ $i ],  '--with-v1',         \$NEED_V1_DB ) )        { next; }
   if ( valid_arg( $ARGV[ $i ],  '--with-v2',         \$NEED_V2_DB ) )        { next; }
   if ( valid_arg( $ARGV[ $i ],  '--with-mysql',      \$NEED_MYSQL ) )        { next; }
   if ( valid_arg( $ARGV[ $i ],  '--with-informix',   \$NEED_INFORMIX ) )     { next; }
   if ( valid_arg( $ARGV[ $i ],  '--with-oracle',     \$NEED_ORACLE ) )       { next; }
   if ( valid_arg( $ARGV[ $i ],  '--with-postgres',   \$NEED_POSTGRES ) )     { next; }
   if ( valid_arg( $ARGV[ $i ],  '--with-session',    \$NEED_SESSION ) )      { next; }

   # Override option defaults
   if ( valid_arg( $ARGV[ $i ],  '--target-dir',      \$TARGET_DIR ) )        { next; }

   # Help options
   if ( valid_arg( $ARGV[ $i ],  '-help',             \$NEED_USAGE ) )        { next; }
   if ( valid_arg( $ARGV[ $i ],  '--help',            \$NEED_USAGE ) )        { next; }

   # UNKNOWN ARG :
   print "Please check your arguments : " . $ARGV[ $i ] . " is not a valid option.\n";
   print_usage();
   exit();

}

# Function      : valid_arg
# Purpose       : Validate an argument to the program.
# Args          :
#        ( value to check against )
#        ( text option for flag )
#        ( variable to set true / false based upon flag )
sub valid_arg {
   local $val        = shift;
   local $option     = shift;
   local $var        = shift;
   local $option_no;
   $option_no     = $option . '=no';
   $option_equal  = $option . '=(.*)';

   if ( $val =~ /$option_no/i ) {
      $$var = 0;
      $VALID_OPT = 1;
      return 1;
   }
   if ( $val =~ /$option_equal/i ) {
      $$var = $1;
      $VALID_OPT = 1;
      return 1;
   }
   if ( $val =~ /$option/i ) {
      $$var = 1;
      $VALID_OPT = 1;
      return 1;
   }
   return 0;
}

if ( $NEED_USAGE || ! $VALID_OPT ) {
   print_usage();
   exit();
}

### -- Build Process -- ###


# Build the libraries for IMP

init_needs_file();
$horde_lib_name = $TARGET_DIR . "/imp.lib";
build_imp_lib();
build_lib();

init_needs_file();
$horde_lib_name = $TARGET_DIR . "/mime.lib";
build_mime_lib();
build_lib();

init_needs_file();
$horde_lib_name = $TARGET_DIR . "/mimetypes.lib";
build_mimetypes_lib();
build_lib();

# Build the database library
init_needs_file();
$horde_lib_name = $TARGET_DIR . "/db.lib";
needs_horde_copyright();
needs_imp_database();
build_lib();

# Build the database creation script
if ( $NEED_IMP ) {
init_needs_file();
$horde_lib_name = needs_imp_sql();
build_lib();
}

sub init_needs_file {
   foreach $file( keys %FILE_COMMENTS ) {
      $FILE_NEEDED{ $file } = 0;
   }
   @INIT_ORDER = ();
}

sub need_file {
   local( $file_name, $comment ) = @_;
   $FILE_COMMENTS{ $file_name } = $comment;
   $FILE_NEEDED{ $file_name } = 1;
}

#### - Different needs functions -> used in the lib functions to setup need this type relationships - ####
sub needs_horde_copyright {
   need_file( 'HordeCopyright.inc',                 '' );
}

sub needs_imp_sql {
   local $v1_sql_root            = 'db/v1';
   local $v2_sql_root            = 'db/v2';
   local $v2_sql_table_defs_root = 'db/v2';
   local $lib_name               = $TARGET_DIR;
   local $db_driver              = '';
   
   if ( $NEED_MYSQL     ) { $db_driver = 'mysql';      }
   if ( $NEED_INFORMIX  ) { $db_driver = 'informix';   }
   if ( $NEED_ORACLE    ) { $db_driver = 'oracle';     }
   if ( $NEED_POSTGRES  ) { $db_driver = 'postgres';   }

   # Default database driver
   if (
      ! $NEED_MYSQL     &&
      ! $NEED_INFORMIX  &&
      ! $NEED_ORACLE    &&
      ! $NEED_POSTGRES  
      )
      {
      $db_driver = 'dummy';
      }

  $lib_name .= '/' . $db_driver . '_create.sql';

  needs_horde_copyright();
  $v2_sql_root                .= '/' . $db_driver . '/sql';
  $v2_sql_table_defs_root     .= '/' . $db_driver . '/sql/table_defs';

   if ( $NEED_V1_DB ) {
   }

   if ( $NEED_V2_DB ) {
      need_file( $v2_sql_root . '/db_create.sql',                                   'Database creation.' );
      need_file( $v2_sql_root . '/create_hordemgr.sql',                             'Create hordemgr user.' );
      need_file( $v2_sql_root . '/create_dbprivs_hordemgr.sql',                     'Create hordemgr privlages.' );
      need_file( $v2_sql_root . '/create_impmgr.sql',                               'Create impmgr user.' );
      need_file( $v2_sql_root . '/create_dbprivs_impmgr.sql',                       'Create impmgr privlages.' );

      #### ---- Table creation items ( only the ones that are implemented are uncommented right now ---- ####
      #need_file( $v2_sql_table_defs_root . '/admin_privlage_grants_table.sql',      'Create table' );
      #need_file( $v2_sql_table_defs_root . '/admin_privlage_table.sql',             'Create table' );
      #need_file( $v2_sql_table_defs_root . '/data_grant_table.sql',                 'Create table' );
      #need_file( $v2_sql_table_defs_root . '/document_config_table.sql',            'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_group_form_grants_table.sql',    'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_group_members_table.sql',        'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_group_modules_grants_table.sql', 'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_group_table.sql',                'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_modules_table.sql',              'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_user_admin_privlages_table.sql', 'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_user_form_grants_table.sql',     'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_user_forms_table.sql',           'Create table' );
      #need_file( $v2_sql_table_defs_root . '/horde_user_modules_grants_table.sql',  'Create table' );
      need_file( $v2_sql_table_defs_root . '/horde_user_table.sql',                  'Create table' );
      #need_file( $v2_sql_table_defs_root . '/imap_server_table.sql',                'Create table' );
      #need_file( $v2_sql_table_defs_root . '/imp_signature_table.sql',              'Create table' );


   }

  return $lib_name;

}

sub needs_imp_database {
   
   local $v1_function_root       = 'db/v1/functions';
   local $v1_includes_root       = 'db/v1/includes';
   local $db_driver              = '';

   if ( $NEED_MYSQL     ) { $db_driver = 'mysql';      }
   if ( $NEED_INFORMIX  ) { $db_driver = 'informix';   }
   if ( $NEED_ORACLE    ) { $db_driver = 'oracle';     }
   if ( $NEED_POSTGRES  ) { $db_driver = 'postgres';   }

   # Default database driver
   if ( ! $NEED_MYSQL     && ! $NEED_INFORMIX  && ! $NEED_ORACLE    && ! $NEED_POSTGRES  ) {
      $db_driver = 'dummy';
      } else {
         if ( $NEED_V1_DB ) {
            # Include the database's table_format.inc
            need_file( $v1_includes_root . '/' . $db_driver . '/table_format.inc',                  'Table format' );
         }
      }

      if ( $NEED_ORACLE ) {
      need_file( $v1_function_root . '/' . $db_driver . '/enterOracle.func',                  'enterOracle function' );
      need_file( $v1_function_root . '/' . $db_driver . '/leaveOracle.func',                  'leaveOracle function' );
      }
      need_file( $v1_function_root . '/' . $db_driver . '/imp_delete_address.func',           'imp_delete_address function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_get_fullname.func',             'imp_get_fullname function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_set_from.func',                 'imp_set_from function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_set_signature.func',            'imp_set_signature function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_add_address.func',              'imp_add_address function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_get_addresses.func',            'imp_get_addresses function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_get_lang.func',                 'imp_get_lang function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_set_fullname.func',             'imp_set_fullname function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_update_address.func',           'imp_update_address function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_check_prefs.func',              'imp_check_prefs function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_get_from.func',                 'imp_get_from function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_get_signature.func',            'imp_get_signature function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_set_lang.func',                 'imp_set_lang function' );
   if ( $NEED_V2_DB ) {
      need_file( 'db/v2/' . $db_driver . '/objects/' . 'HordeDb.object',                      'HordeDb object' );
      need_file( 'db/v2/' . $db_driver . '/objects/' . 'HordeDb_User.object',                 'HordeDb_User object' );
   }

   # Only mysql & postgres support for sessions at the moment 
   if($NEED_MYSQL) {
      need_file( $v1_function_root . '/' . $db_driver . '/imp_get_session.func',            'imp_get_session function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_set_session.func',            'imp_set_session function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_purge_sessions.func',         'imp_purge_sessions function' );
   }
   if($NEED_POSTGRES) {
      need_file( $v1_function_root . '/' . $db_driver . '/imp_open_pg_db.func',            'imp_open_pg_db function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_get_session.func',            'imp_get_session function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_set_session.func',            'imp_set_session function' );
      need_file( $v1_function_root . '/' . $db_driver . '/imp_purge_sessions.func',         'imp_purge_sessions function' );
   }

}

sub needs_imp_defaults_objects {
   need_file( 'ImpDefaults.object',                   'ImpDefaults Object' );
   need_file( 'SSLDefaults.object',                   'SSLDefaults Object' );
   need_file( 'CyrusDefaults.object',                 'CyrusDefaults Object' );
   need_file( 'IMAPServer.object',                    'IMAPServer Object' );
   need_file( 'ImpUserDefaults.object',               'ImpUserDefaults Object' );
}

sub build_mime_lib {
   needs_horde_copyright();
   need_file( 'mime_part.object',                  'mime_part     - MimeLib: Copyright 1998 Patrick C. Audley paudley@blackcat.ca' );
   need_file( 'mime_message.object',               'mime_message  - MimeLib: Copyright 1998 Patrick C. Audley paudley@blackcat.ca' );
}

sub build_mimetypes_lib {
   need_file( 'InitMimeTypes.init',                'InitMimeTypes' );
   need_file( 'mime_part_data.object',             'mime_part_data object' );
   need_file( 'mime_action_ximpdata.func',         'mime_action_ximpdata function' );
   need_file( 'mime_action_images.func',           'mime_action_images function' );
   need_file( 'mime_view_msword.func',             'mime_view_msword function' );
   need_file( 'mime_view_html.func',               'mime_view_html function' );
   need_file( 'mime_view_rpm.func',                'mime_view_rpm function' );
   need_file( 'mime_view_text.func',               'mime_view_text function' );
   need_file( 'mime_view_tgz.func',                'mime_view_tgz function' );
   need_file( 'mime_view_zip.func',                'mime_view_zip function' );
}

sub build_imp_lib {
   
   needs_horde_copyright();
   needs_imp_defaults_objects();

   need_file( 'ImpLibVersion.def',                 'ImpLibrary Version' );
   need_file( 'IncludeImpLib.init',                'Include Imp Lib' );
   need_file( 'IncludeHordeLib.init',              'Include Horde Lib' );
   need_file( 'IncludeDbLib.init',                 'Include Db Lib' );
   need_file( 'InitImpDefaults.init',              'Init Imp Defaults object' );
   need_file( 'InitHelp.init',                     'Init Horde Help' );
   need_file( 'DbLibVersion.def',                  'Imp Database Library Version' );
   
   # Imp specific objects
   need_file( 'ImapServers.def',                   'IMAP Servers' );
   need_file( 'ImpActions.def',                    'IMP - Form Action Defines' );
   need_file( 'ImpUserSignature.object',           'ImpUserSignature Object' );
   need_file( 'ImpUser.object',                    'ImpUser Object' );
   need_file( 'ImpCookies.object',                 'IMP - Cookies Object' );
   need_file( 'ImpSession.object',                 'IMP - Session Object' );
   need_file( 'LDAPServer.object',                 'LDAPServer Object' );

   # Imp specific functions
   need_file( 'wrap_message.func',                 'Message wrapping function.' );
   need_file( 'textwrap.func',                     'textwrap function' );
   need_file( 'get_barefrom.func',                 'get_barefrom function' );
   need_file( 'decode_mime_string.func',           'decode_mime_string function' );
   need_file( 'full_mailbox_list.func',            'full_mailbox_list function' );        # -- Mailbox listing functions --
   need_file( 'mailbox_list.func',                 'mailbox_list function' );             # -- Mailbox listing functions --
   need_file( 'reload_frame.func',                 'reload_frame function' );
   need_file( 'validate_login.func',               'validate_login function' );
   need_file( 'status.func',                       'status function' );
   need_file( 'caching_headers.func',              'caching_headers function' );
   #need_file( 'init_db.func',                      'init_db function' );
   need_file( 'object_destructor.func',            'object destructor function' );
   need_file( 'create_session_object.func',        'creates ImpSession object function' );

   # Language stuff
   need_file( 'select_lang.func',                  'select_lang function' );
   need_file( 'mytrim.func',                       'mytrim function' );
   need_file( 'valid_lang.func',                   'valid_lang function' );

   need_file( 'include_lynx_menu.func',            'include_lynx_menu' );
}

##### --- #####
sub build_lib {

   print "Building : $horde_lib_name\n";
	open( HORDE_LIB, "> $horde_lib_name" )
   	|| die "ERROR : Could not open horde lib for writing.\nEXITING\nERROR : $!\n";

	print HORDE_LIB "<?php\n\n";
   print "\n\tIncludes :\n";
   build_ext_file( HORDE_LIB, "inc" );
   print "\n\tDefines :\n";
   build_ext_file( HORDE_LIB, "def" );
   print "\n\tObjects :\n";
   build_ext_file( HORDE_LIB, "object" );
   print "\n\tFunctions :\n";
   build_ext_file( HORDE_LIB, "func" );
   print "\n\tInit :\n";
   build_ext_file( HORDE_LIB, "init" );
   print "\n\tSql  :\n";
   build_ext_file( HORDE_LIB, "sql" );

   print "\n";
	print HORDE_LIB "?>\n";
	close( HORDE_LIB );
}

sub build_ext_file {
   local( *OUT_FH, $ext_to_process )  = @_;
   if ( $ext_to_process ne "init" ) {
	   foreach $file_key ( sort keys %FILE_COMMENTS ) {
   	   ( @temp_data ) = split( /\./, $file_key );
	      $file_ext = $temp_data[ ( @temp_data - 1) ];
  	 	   $base_dir = '';
         if ( $file_ext ne $ext_to_process ) {     next; }
         if ( $FILE_NEEDED{ $file_key } != 1 ) {   next; }
  		   if ( $file_ext eq "inc"    ) {   $base_dir = $inc;  }
   	   if ( $file_ext eq "def"    ) {   $base_dir = $def;  }
   	   if ( $file_ext eq "func"   ) {   $base_dir = $func; }
   	   if ( $file_ext eq "object" ) {   $base_dir = $obj;  }
         if ( $file_ext eq "init" )   {   $base_dir = $init; }
         if ( $file_ext eq "object" && $file_key =~ /Html/ ) { 
            $base_dir .= "Html/";
         }
         if ( $file_key =~ /\// ) { # It's already got a path in it 
            $base_dir = '';
         };
   	   add_file( OUT_FH, $base_dir . $file_key, $FILE_COMMENTS{ $file_key } );
	   }

   } else {
	   foreach $file_key ( sort keys %FILE_COMMENTS ) {
   	   ( @temp_data ) = split( /\./, $file_key );
	      $file_ext = $temp_data[ ( @temp_data - 1) ];
  	 	   $base_dir = '';
         if ( $file_ext ne $ext_to_process ) {     next; }
         if ( $FILE_NEEDED{ $file_key } != 1 ) {   next; }
         if ( $file_ext eq "init" )   {   $base_dir = $init; }
   	   add_file( OUT_FH, $base_dir . $file_key, $FILE_COMMENTS{ $file_key } );
      }

   }
}

sub add_file {
   local( *OUT_FH, $filename, $comment ) = @_;
   print "\tAdding file : $filename\n";

   if ( $comment ne "" ) {
   print OUT_FH <<"FILE_COMMENT";
/*
$comment      : $filename
*/
FILE_COMMENT
   }

   open( IN_FH, $filename ) || warn "WARNING : Unable to open : $filename\nERROR : $!\n";
   while( <IN_FH> ) { print OUT_FH $_; }
   close( IN_FH );   

   print OUT_FH <<"EOF";
/*      EOF - $filename       */



EOF

}

sub print_usage {
   print <<"USAGE"

buildlib.pl : IMP Library build program.

   This program builds a client library for IMP.

   Available option flags :
      Database flags -

         --with-v1[=no]

            Turns on/off the v1 database functions. Needed for
            compatibility with pre v2 imp versions.

         --with-v2[=no]

            Turns on/off the v2 database functions.

         --with-mysql[=no]
         --with-informix[=no]
         --with-oracle[=no]
         --with-postgres[=no]

            Turns on/off the support for that database.

         --with-session[=no]

            Turns on/off support for the databased session support.

      Output flags -         

         --target-dir=[ Output directory ]  

            Changes the output directory for the libraries.
      
      Help flags -

         -help
         --help


USAGE
}
