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