#!/usr/bin/perl -w
#---------------------------------------------------------------------
# gsgsmppin
# Alamin GSM SMS Gateway SMPP output interface
#---------------------------------------------------------------------
# (C) Andrs Seco Hernndez, April 2000-Oct 2004
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
#---------------------------------------------------------------------

=pod

=head1 NAME

gsgsmppout - Alamin GSM SMS Gateway SMPP output interface

=head1 SYNOPSIS

gsgsmppout [-c config_file_name]

=head1 DESCRIPTION

gsgsmppout is the component that sends messages to a SMSC with a SMPP
interface. Connect parameters are configured using its config file.

=head1 OPTIONS

=over

=item -c <file_name>

(default: /etc/alamin/gsgsmppout.conf) Sets the config file to be used. It is a perl formated file, be careful with the perl syntax.

=back

=head1 FILES

/etc/alamin/gsgsmppout.conf

=head1 SEE ALSO

See also gsgc(1), gsgcmd(8), gsgmdd(8), gsgsmppin(8), gsgsmppout(8) and
gsgdb2sms(8).

=head1 BUGS

Send bugs to the author, please. I would like to keep the program without
bugs.

=head1 LICENSE

Alamin GSM SMS Gateway
Copyright (C) Andres Seco Hernandez and others.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

=head1 AUTHOR

Andres Seco Hernandez <AndresSH@alamin.org>.

=cut

use strict;

my $timetoterminate = 0;
$SIG{TERM} = \&TERMINATE;

use Sys::Syslog qw(:DEFAULT setlogsock);
use Getopt::Std;
use Net::SMPP;

my $program_name = "gsgsmppout";
my $program_version = "v0.3.7 - Oct 25, 2004";

my $waittime = 1;
my $verbose = 1;
my $debug = 1;
my $usesyslog = 1;
my $syslogfacility = "local0";
my $pidfile = "/var/run/alamin/gsgsmppout.pid";
my $runasdaemon = 1;
my $smpphost = 'smpphost';
my $smppport = 1234;
my $smppvers = 0x34;
my $smppuser = "smppuser";
my $smpppass = "smpppass";
my $smpptout = 30;
my $smppenquireloop = 30;
my $spoolpath = '/var/spool/alamin/smpp-out';

my %opt;
getopts ("c:", \%opt);
my $configfile = $opt{"c"} || "/etc/alamin/gsgsmppout.conf";
eval `cat $configfile`;

if ($runasdaemon) {
  use Proc::Daemon;
  Proc::Daemon::Init;
}

setlogsock "unix";
openlog($program_name,"pid",$syslogfacility);
umask 007;
open (PIDFILE,">".$pidfile);
print PIDFILE "$$";
close (PIDFILE);
logit("info","Starting Alamin GSM SMS Gateway - $program_name - $program_version") if ($verbose);

my $smpp;
my $resp;
my $counter = 0;

while(!$timetoterminate) {
  eval {
    $smpp = Net::SMPP->new_transmitter($smpphost, port => $smppport,
                                       smpp_version => $smppvers, timeout => $smpptout,
                                       system_id => $smppuser, password => $smpppass);
  };
  if (!$@ && $smpp) {
    my $connected = 1;
    while (!$timetoterminate && $connected) {
# buscar archivo
      opendir (DIRH,$spoolpath);
      my $result;
      my $morefiles = 1;
      while (!$timetoterminate && $connected && $morefiles) {
        $result = readdir(DIRH);
        if ($result) {
          if ($result =~ /^\./) { next; }
          open (MSGFILE,"<".$spoolpath."/".$result);
          my $line_counter = 0;
          my $smpp_to = "";
          my $smpp_smsc = "";
          my $smpp_message = "";
          while (<MSGFILE>) {
            chomp; if (/\r$/) { chop; } chomp;
            $line_counter++;
            if ($line_counter == 1) {
              my @numbers = split (/\s+/,$_);
              $smpp_to = $numbers[0];
              next;
            }
            $smpp_message = $smpp_message.$_."\n";
          }
          close (MSGFILE);
          chomp ($smpp_message);
          eval {
            $resp = $smpp->submit_sm(destination_addr => $smpp_to, short_message => $smpp_message);
          };
          if (!$@) {
            if (!$resp->{status}) {
              unlink $spoolpath."/".$result;
              logit("info","OK sending message to $smpp_to.") if ($verbose);
            } else {
              logit("info","ERROR sending message to $smpp_to.") if ($verbose);
            }
          } else {
            $connected = 0;
          }
        } else {
          $morefiles = 0;
        }
      }
      closedir (DIRH);
# espera 1
      if (!$timetoterminate) {
        logit("debug","Waiting $waittime seconds.") if ($debug);
        sleep $waittime;
      }
      if (!$timetoterminate && $connected) {
        $counter++;
# si contador = 20 - poner a 0 y enquire_link
        if ($counter > $smppenquireloop) {
          eval {
            $resp = $smpp->enquire_link();
          };
          if (!$@) {
            logit("debug","Sent enquire_link.") if ($debug);
            $counter = 0;
          } else {
            $connected = 0;
          }
        }
      }
    }
  }
  if (!$timetoterminate) {
    my $rewaittime = $waittime * 2;
    logit("warning","Lose SMPP connection, reconnecting in $rewaittime seconds.") if ($verbose);
    sleep $rewaittime;
  }
}

logit("info","Exiting.") if ($verbose);
unlink $pidfile;
closelog;

if ($smpp) {
  $smpp->unbind();
}

sub TERMINATE {
  $timetoterminate = 1;
  logit("debug","SIGTERM received, ending tasks...") if ($debug);
}

sub logit {
  my ($log_type, $log_message) = @_;
  if ($usesyslog) {
    syslog($log_type,$log_message);
  }
}
