##################################################
#
# GiantDisc mp3 Jukebox
# 
# © 2000, Rolf Brugger
#
##################################################

package gdparams;

#use lib '/usr/local/bin';
use strict;
use Getopt::Long;

my @mp3dirs;

############################################################
### Global variables (accessible from anywhere)

# IMPORTANT ERROR!  all modules refer to gdparms::varname instead
# of gdparams::varname
# ... however, it works ... I just don't know why  :-/


#my ($dbhost, $shutdowncmd, $extmp3player, $defrecbitrate,
#    $systemonline);


### Global constants


############################################################
###

sub get_configfilename{
  # Parameters: @ARGV (implicit)
  # returns the name of the configuration file
  # 
  # the config-file is the first parameter to gdd.pl

  my ($cfgfilename);

  Getopt::Long::Configure("pass_through");  # leave all parameters in ARGV, except for --cfg
  GetOptions("cfg:s" => \$cfgfilename);   # --cfg config-file

  if (length($cfgfilename)>0){
    return ($cfgfilename);
  }
  else{
    return gdbase()."/.gdconfig";
  }
}

############################################################
###

sub get_configfile_params{
  ### Parameters: Call-by-reference

  my ($cfgfilename,
    $dbhost, 
    $commmode,
    $serialdevice, $serialspeed,
    $tcpiphost, $tcpipport,
    $playerhost, $playertype, $playerdevice, 
    $logtarget )        = @_;
    

  if (-e "$cfgfilename"){
    ### Read configuration file im home directory
    open (CONF, "< ".$cfgfilename)
      or die "Error: could not open configuration file $cfgfilename\n";
      
    my $line;
    while(<CONF>){
      $line = $_;
      chop $line;
      $line =~ tr/\r/ /;
      # \w word-char
      # \w non-word-char
      # \s whitespace-char
      # \S non-whitespace-char
  
      if($line =~ m/^dbhost.*=\s*(\S+)/i ){
        $$dbhost = $1;
      }
  
      if($line =~ m/^commmode.*=\s*([0-9]+)/i ){
        $$commmode = $1;
      }
  
      if($line =~ m/^serialdevice.*=\s*([\w\/]+)/i ){
        $$serialdevice = $1;
      }
  
      if($line =~ m/^serialspeed.*=\s*([0-9]+)/i ){
        $$serialspeed = $1;
      }
  
      if($line =~ m/^tcpiphost.*=\s*(\S+)/i ){
        $$tcpiphost = $1;
      }
  
      if($line =~ m/^tcpipport.*=\s*([0-9]+)/i ){
        $$tcpipport = $1;
      }
  
      if($line =~ m/^playerhost.*=\s*(\S+)/i ){
        $$playerhost = $1;
      }
  
      if($line =~ m/^playertype.*=\s*([0-9]+)/i ){
        $$playertype = $1;
      }
  
      if($line =~ m/^playerdevice.*=\s*(\S+)/i ){
        $$playerdevice = $1;
      }
  
      if($line =~ m/^logtarget.*=\s*(\w+)/i ){
        if ($1 eq "stdout" || $1 eq "logfile" || $1 eq "devnull"){
          $$logtarget = $1;
        }
      }
    }
    close (CONF);
  }

  
}

############################################################

sub configfile_to_db{
  ### blindly read all settings into database, although a few parameters are already read
  # the routine does nothing, if teh file doesn't exist
  my ($dbh, $playerid, $cfgfilename)        = @_;


  if (-e "$cfgfilename"){
    ### Read configuration file
#   open (CONF, "< ".gdbase()."/.gdconfig")
    open (CONF, "< ".$cfgfilename)
    or die "Error: could not open configuration file $cfgfilename\n";
      
    my ($line, $name, $value);
    while(<CONF>){
      $line = $_;
      chop $line;
      $line =~ tr/\r/ /;
      # \w word-char
      # \w non-word-char
      # \s whitespace-char
      # \S non-whitespace-char
  
      # match:
      #   a line not starting with '#'
      #   a parameter name without spaces, followed by
      #   an equal sign, followed by
      #   a parameter value, which is anything to end of line
      if($line =~ m/^(\w+)\s*=\s*(.*)\s*$/i ){ 
        $name  = $1;
        $value = $2;
        #print "Config-Param: '$name'='$value'\n";
        if ($name ne "keymap"){ # ignore 'keymap'. This is a temporary workaround! 
          my $retval = $dbh->do("REPLACE INTO parameter SET "
          ."playerid = '$playerid', "
          ."name     = '$name', "
          ."value    = '$value' ");
        }
      }
    }
    close (CONF);
  }
}


############################################################
###

sub get_otherclients_params{
  ### Parameters: Call-by-reference

  my ($keymap,  # type: reference to an empty hash
    $cfgfilename
    )= @_;

  
  if (-e "$cfgfilename"){
    ### Read configuration file im home directory
    open (CONF, "< ".gdbase()."/.gdconfig")
  #  open (CONF, "< ".$cfgfilename)
      or die "Error: could not open configuration file .gdconfig\n";
      
    my $line;
    while(<CONF>){
      $line = $_;
      chop $line;
      $line =~ tr/\r/ /;
      # \w word-char
      # \w non-word-char
      # \s whitespace-char
      # \S non-whitespace-char
  
      if($line =~ m/^keymap.*=\s*(\S+)\s*-\s*(\S+)\s*$/i ){
        print ("keymap: key: $1, val: $2\n");
        $$keymap{$1} = $2;
      }
    }
    close (CONF);
  }
}


############################################################
### translate logtarget string to integer
sub logtarget_to_int{
  my ($logtargetstr) = @_;
  if ($logtargetstr eq "devnull") {return 0;}
  if ($logtargetstr eq "logfile") {return 1;}
  if ($logtargetstr eq "stdout" ) {return 2;}
  return 2; # default
}


############################################################
###

sub get_commandline_params{

  my ($dbhost, 
    $commmode,
    $serialdevice, $serialspeed,
    $tcpiphost, $tcpipport,
    $playerhost, $playertype, $playerdevice, 
    $logtarget)         = @_;
    # ARGV passed implicitly


  my $help;
  Getopt::Long::Configure("no_pass_through");  # check all parameters in ARGV
  GetOptions(
    "help"       => \$help, 
    "dbhost:s"   => $dbhost,    # $dbhost is already a reference
    "commmode:i"     => $commmode,
    "serialdevice:s" => $serialdevice,
    "serialspeed:i"  => $serialspeed,
    "tcpiphost:s"    => $tcpiphost,
    "tcpipport:i"    => $tcpipport,
    "playertype:i"   => $playertype,
    "playerhost:s"   => $playerhost,
    "playerdevice:s" => $playerdevice,
    "logtarget:s"    => $logtarget
    );

  if ($help){
  print <<EOF;
gdd.pl: GiantDisc Server Script
Option         possible values  

--dbhost (string)          address or hostname of mysql database server
                           Default value: localhost    

--commmode (number)        Communication mode between Palm and server.
                           1: serial line RS232
                           2: generic TCP/IP (server - accepts incoming connections)
                           3: generic TCP/IP (client - connects to server)
                           Default value: 1

--serialdevice (string)    Device, where Palm is connected to. 
                           Only used if --commmode 1
                           Default value: /dev/ttyS0

--serialspeed  (number)    Communication speed over serial line in
                           Bits per second.
                           Only used if --commmode 1
                           Default value: 19200

--tcpiphost (string)       Host, that accepts socket connections.
                           Only used if --commmode 2 or 3
                           Default value: localhost
                                  
--tcpipport  (number)      Port used for TCP/IP communication mode.
                           Only used if --commmode 2 or 3
                           Default value: 26468

--playertype (number)      main audio out device type
                           0:  soundcard (first audio channel)
                           20: network attached audio streaming device
                           Default value: 0

--playerhost (string)      address or hostname where the audio stream
                           is sent to.
                           playertype 0:  host of soundcard (not used)
                           playertype 20: audio stream decoder host
                           Default value: localhost

--playerdevice  (string)   Device where audio stream is sent to.
                           playertype 0:  soundcard device (not used)
                           playertype 20: port number of TCP stream
                           Default value: 2020

--logtarget    stdout,     Target, where log-messages of the 
               logfile,    server script should be sent to. 
               or devnull  'stdout' sends to standard out, 'logfile'
                           sends to a log file in ~music/tmp and
                           devnull supresses all logging.
                           Default value: stdout

--cfg  (string)            Specifies a configuration file other than
                           the default configuration file ~/.gdconfig

EOF
  exit 0;
  }
}


############################################################
###

sub gdbase{ # returns base path of gd files 
        # The path must not end with a slash!
  return "/home/music";
}

sub mp3dirs{    # returns list of mp3 directories
        # Scans the music directory for 2-digit directories

  opendir MUSICDIR, gdbase() or die "ERROR: can't scan music directory\n";
  @mp3dirs = sort (grep /^[0-9][0-9]$/ , readdir MUSICDIR);
  closedir MUSICDIR;
  #print "MP3dirs: ",@mp3dirs, "\n";
  return ( @mp3dirs );
}




1;
#
