Merge branch 'patch-19' of https://github.com/gjones2/Freeside
[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 $file_timestamp = $filename.'-'.time2str('%Y-%m-%d', time);
109
110   my $import_options = {
111     'file'            => "$cachedir/$ungziped",
112     'format'          => $format,
113     'batch_namevalue' => $file_timestamp,
114     'empty_ok'        => 1,
115   };
116   $import_options->{'cdrtypenum'} = $opt_c if $opt_c;
117   
118   my $error = FS::cdr::batch_import($import_options);
119   if ( $error ) {
120     unlink "$cachedir/$filename";
121     unlink "$cachedir/$ungziped" if $opt_g;
122     die $error;
123   }
124
125   if ( $opt_d ) {
126     if($opt_m eq 'ftp') {
127       my $ftp = ftp();
128       $ftp->rename($filename, "$opt_d/$file_timestamp")
129         or do {
130           unlink "$cachedir/$filename";
131           unlink "$cachedir/$ungziped" if $opt_g;
132           die "Can't move $filename to $opt_d: ".$ftp->message . "\n";
133         };
134     }
135     else {
136       my $sftp = sftp();
137       $sftp->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: ". $sftp->error . "\n";
142         };
143     }
144   }
145
146   unlink "$cachedir/$filename";
147   unlink "$cachedir/$ungziped" if $opt_g;
148
149 }
150
151 ###
152 # subs
153 ###
154
155 sub usage {
156   "Usage: \n  cdr.import user format servername\n";
157 }
158
159 use vars qw( $sftp $ftp );
160
161 sub ftp {
162   return $ftp if $ftp && $ftp->pwd;
163   
164   my ($hostname, $userpass) = reverse split('@', $servername);
165   my ($ftp_user, $ftp_pass) = split(':', $userpass);
166
167   my $ftp = Net::FTP->new($hostname, %options) 
168     or die "FTP connection to '$hostname' failed.";
169   $ftp->login($ftp_user, $ftp_pass) or die "FTP login failed: ".$ftp->message;
170   $ftp->cwd($opt_r) or die "can't chdir to $opt_r\n" if $opt_r;
171   return $ftp;
172 }
173
174 sub sftp {
175
176   #reuse connections
177   return $sftp if $sftp && $sftp->cwd;
178
179   my %sftp = ( host => $servername );
180
181   $sftp = Net::SFTP::Foreign->new(%sftp);
182   $sftp->error and die "SFTP connection failed: ". $sftp->error;
183
184   $sftp;
185 }
186
187 =head1 NAME
188
189 freeside-cdr-sftp_and_import - Download CDR files from a remote server via SFTP
190
191 =head1 SYNOPSIS
192
193   cdr.sftp_and_import [ -m method ] [ -p prefix ] [ -e extension ] 
194     [ -r remotefolder ] [ -d donefolder ] [ -v level ] [ -P port ]
195     [ -a ] [ -c cdrtypenum ] user format [sftpuser@]servername
196
197 =head1 DESCRIPTION
198
199 Command line tool to download CDR files from a remote server via SFTP 
200 or FTP and then import them into the database.
201
202 -m: transfer method (sftp or ftp), defaults to sftp
203
204 -p: file prefix, if specified
205
206 -e: file extension, defaults to .csv
207
208 -r: if specified, changes into this remote folder before starting
209
210 -d: if specified, moves files to the specified folder when done
211
212 -P: if specified, sets the port to use
213
214 -a: use ftp passive mode
215
216 -v: set verbosity level; this script only has one level, but it will 
217     be passed as the 'debug' argument to the transport method
218
219 -c: cdrtypenum to set, defaults to none
220
221 -g: File is gzipped
222
223 user: freeside username
224
225 format: CDR format name
226
227 [sftpuser@]servername: remote server
228 (or ftpuser:ftppass@servername)
229
230 =head1 BUGS
231
232 =head1 SEE ALSO
233
234 L<FS::cdr>
235
236 =cut
237
238 1;
239