stretch
[freeside.git] / bin / sqlradius-nas.import
1 #!/usr/bin/perl -w
2
3 use strict;
4 use DBI;
5 use FS::UID qw(adminsuidsetup); #datasrc
6 use FS::Record qw(qsearch qsearchs dbh);
7 use FS::nas;
8 use FS::export_nas;
9 use FS::part_export;
10
11 my $user = shift or die &usage;
12 adminsuidsetup $user;
13
14 $FS::export_nas::noexport_hack = 1;
15 $FS::UID::AutoCommit = 0;
16 my $dbh = dbh;
17
18 my $exportnum = shift or die &usage;
19 my $part_export = qsearchs('part_export', { exportnum => $exportnum })
20   or die "export $exportnum not found.\n";
21
22 $part_export->isa('FS::part_export::sqlradius')
23   or die "export $exportnum is not an sqlradius export.\n";
24
25 my $raddbh = DBI->connect(
26   $part_export->option('datasrc'),
27   $part_export->option('username'),
28   $part_export->option('password')
29 );
30
31 # cache NAS names we already know about, and don't import them
32 my %existing_names = map { $_->nasname , $_->nasnum } qsearch('nas', {});
33
34 my @fields = (qw( nasname shortname type secret server community description ));
35 my $sql = 'SELECT '.join(', ',@fields).' FROM nas';
36 my $all_nas = $raddbh->selectall_arrayref($sql)
37   or die "unable to retrieve NAS records: ".$dbh->errstr."\n";
38
39 warn scalar(@$all_nas)." records found.\n";
40 my $inserted = 0;
41 foreach my $row (@$all_nas) {
42   my %hash;
43   @hash{@fields} = @$row;
44   if (my $num = $existing_names{ $hash{nasname} }) {
45     warn "NAS $hash{nasname} already exists as #$num (skipped)\n";
46   }
47   else {
48     my $nas = FS::nas->new(\%hash);
49     my $error = $nas->insert 
50              || $nas->process_m2m(link_table => 'export_nas',
51                                   target_table => 'part_export',
52                                   params => [ $exportnum ]);
53     if ( $error ) {
54       $dbh->rollback;
55       die "error inserting $hash{nasname}: $error (changes reverted)\n";
56     }
57     $inserted++;
58   }
59 } #foreach $row
60
61 warn "Inserted $inserted NAS records.\n\n";
62 $dbh->commit;
63
64 sub usage {
65   die "Usage:\n\n  sqlradius-nas.import user exportnum\n\n";
66 }
67