bae8051514fb29396fe4b2dc9d55ecc23dff6217
[freeside.git] / FS / bin / freeside-cdr-sftp_and_import
1 #!/usr/bin/perl
2
3 use strict;
4 use Getopt::Std;
5 use Date::Format;
6 use Net::SFTP::Foreign::Compat;
7 use Net::FTP;
8 use FS::UID qw(adminsuidsetup datasrc);
9 use FS::cdr;
10
11 ###
12 # parse command line
13 ###
14
15 use vars qw( $opt_m $opt_p $opt_r $opt_e $opt_d $opt_v $opt_P $opt_a $opt_c $opt_i $opt_g $opt_s $opt_b );
16 getopts('c:i:m:p:r:e:d:v:P:agsb');
17
18 $opt_e ||= 'csv';
19 #$opt_e = ".$opt_e" unless $opt_e =~ /^\./;
20 $opt_e =~ s/^\.//;
21
22 $opt_p ||= '';
23
24 die "invalid cdrtypenum" if $opt_c && $opt_c !~ /^\d+$/;
25 die "invalid carrierid"  if $opt_i && $opt_i !~ /^\d+$/;
26
27 my %options = ();
28
29 my $user = shift or die &usage;
30 adminsuidsetup $user;
31
32 # %%%FREESIDE_CACHE%%%
33 my $cachedir = '%%%FREESIDE_CACHE%%%/cache.'. datasrc. '/cdrs';
34 mkdir $cachedir unless -d $cachedir;
35
36 my $format = shift or die &usage;
37
38 use vars qw( $servername );
39 $servername = shift or die &usage;
40
41 ###
42 # get the file list
43 ###
44
45 warn "Retrieving directory listing\n" if $opt_v;
46
47 $opt_m = 'sftp' if !defined($opt_m);
48 $opt_m = lc($opt_m);
49
50 my $ls;
51
52 if($opt_m eq 'ftp') {
53   $options{'Port'}    = $opt_P if $opt_P;
54   $options{'Debug'}   = $opt_v if $opt_v;
55   $options{'Passive'} = $opt_a if $opt_a;
56
57   my $ls_ftp = ftp();
58
59   $ls = [ grep { /^$opt_p.*\.$opt_e$/i } $ls_ftp->ls ];
60 }
61 elsif($opt_m eq 'sftp') {
62   $options{'port'}    = $opt_P if $opt_P;
63   $options{'debug'}   = $opt_v if $opt_v;
64
65   my $ls_sftp = sftp();
66
67   $ls_sftp->setcwd($opt_r) or die "can't chdir to $opt_r\n"
68     if $opt_r;
69
70   $ls = $ls_sftp->ls('.', wanted => qr/^$opt_p.*\.$opt_e$/i,
71                           names_only => 1 );
72 }
73 else {
74   die "Method '$opt_m' not supported; must be ftp or sftp\n";
75 }
76
77 ###
78 # import each file
79 ###
80
81 foreach my $filename ( @$ls ) {
82
83   warn "Downloading $filename\n" if $opt_v;
84
85   #get the file
86   if($opt_m eq 'ftp') {
87     my $ftp = ftp();
88     $ftp->get($filename, "$cachedir/$filename")
89       or die "Can't get $filename: ". $ftp->message . "\n";
90   }
91   else {
92     my $sftp = sftp();
93     $sftp->get($filename, "$cachedir/$filename")
94       or die "Can't get $filename: ". $sftp->error . "\n";
95   }
96
97   warn "Processing $filename\n" if $opt_v;
98  
99   my $ungziped = $filename;
100   $ungziped =~ s/\.gz$//;
101   if ( $opt_g ) {
102       if(system('gunzip', "$cachedir/$filename") != 0) {
103         warn "gunzip of '$cachedir/$filename' failed" if $opt_v;
104         unlink "$cachedir/$filename";
105         next;
106       }
107   }
108
109   my $file_timestamp = $filename.'-'.time2str('%Y-%m-%d', time);
110
111   my $import_options = {
112     'file'            => "$cachedir/$ungziped",
113     'format'          => $format,
114     'batch_namevalue' => $file_timestamp,
115     'empty_ok'        => 1,
116   };
117   $import_options->{'cdrtypenum'} = $opt_c if $opt_c;
118   $import_options->{'carrierid'}  = $opt_i if $opt_i;
119   
120   my $error = FS::cdr::batch_import($import_options);
121
122   if ( $error ) {
123
124     if ( $opt_s ) {
125       warn "$ungziped: $error\n";
126     } else {
127       unlink "$cachedir/$filename";
128       unlink "$cachedir/$ungziped" if $opt_g;
129       die $error;
130     }
131
132   } else {
133
134     if ( $opt_d ) {
135       if ( $opt_m eq 'ftp') {
136         my $ftp = ftp();
137         $ftp->rename($filename, "$opt_d/$file_timestamp")
138           or do {
139             unlink "$cachedir/$filename";
140             unlink "$cachedir/$ungziped" if $opt_g;
141             die "Can't move $filename to $opt_d: ".$ftp->message . "\n";
142           };
143       } else {
144         my $sftp = sftp();
145         $sftp->rename($filename, "$opt_d/$file_timestamp")
146           or do {
147             unlink "$cachedir/$filename";
148             unlink "$cachedir/$ungziped" if $opt_g;
149             die "can't move $filename to $opt_d: ". $sftp->error . "\n";
150           };
151       }
152     }
153
154   }
155
156   unlink "$cachedir/$filename";
157   unlink "$cachedir/$ungziped" if $opt_g;
158
159 }
160
161 ###
162 # subs
163 ###
164
165 sub usage {
166   "Usage:
167   cdr.sftp_and_import [ -m method ] [ -p prefix ] [ -e extension ] 
168     [ -r remotefolder ] [ -d donefolder ] [ -v level ] [ -P port ]
169     [ -a ] [ -g ] [ -s ] [ -c cdrtypenum ] user format [sftpuser@]servername
170   ";
171 }
172
173 use vars qw( $sftp $ftp );
174
175 sub ftp {
176   return $ftp if $ftp && $ftp->pwd;
177   
178   my ($hostname, $userpass) = reverse split('@', $servername);
179   my ($ftp_user, $ftp_pass) = split(':', $userpass);
180
181   my $ftp = Net::FTP->new($hostname, %options) 
182     or die "FTP connection to '$hostname' failed.";
183   $ftp->login($ftp_user, $ftp_pass) or die "FTP login failed: ".$ftp->message;
184   $ftp->cwd($opt_r) or die "can't chdir to $opt_r\n" if $opt_r;
185   $ftp->binary or die "can't set BINARY mode: ". $ftp->message if $opt_b;
186   return $ftp;
187 }
188
189 sub sftp {
190
191   #reuse connections
192   return $sftp if $sftp && $sftp->cwd;
193
194   my %sftp = ( host => $servername );
195
196   $sftp = Net::SFTP::Foreign->new(%sftp);
197   $sftp->error and die "SFTP connection failed: ". $sftp->error;
198
199   $sftp;
200 }
201
202 =head1 NAME
203
204 freeside-cdr-sftp_and_import - Download CDR files from a remote server via SFTP
205
206 =head1 SYNOPSIS
207
208   freeside-cdr-sftp_and_import [ -m method ] [ -p prefix ] [ -e extension ] 
209     [ -r remotefolder ] [ -d donefolder ] [ -v level ] [ -P port ]
210     [ -a ] [ -g ] [ -s ] [ -c cdrtypenum ] [ -i carrierid]
211     user format [sftpuser@]servername
212
213 =head1 DESCRIPTION
214
215 Command line tool to download CDR files from a remote server via SFTP 
216 or FTP and then import them into the database.
217
218 -m: transfer method (sftp or ftp), defaults to sftp
219
220 -p: file prefix, if specified
221
222 -e: file extension, defaults to .csv
223
224 -r: if specified, changes into this remote folder before starting
225
226 -d: if specified, moves files to the specified folder when done
227
228 -P: if specified, sets the port to use
229
230 -a: use ftp passive mode
231
232 -b: use ftp binary mode
233
234 -v: set verbosity level; this script only has one level, but it will 
235     be passed as the 'debug' argument to the transport method
236
237 -c: cdrtypenum to set, defaults to none
238
239 -i: carrierid to set, defaults to none
240
241 -g: File is gzipped
242
243 -s: Warn and skip files which could not be imported rather than abort
244
245 user: freeside username
246
247 format: CDR format name
248
249 [sftpuser@]servername: remote server
250 (or ftpuser:ftppass@servername)
251
252 =head1 BUGS
253
254 =head1 SEE ALSO
255
256 L<FS::cdr>
257
258 =cut
259
260 1;
261