summaryrefslogtreecommitdiff
path: root/FS/bin/freeside-sqlradius-dedup-group
blob: 441d50f62497a57ddd3331a5e9e9bea319ec776d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/perl -w

use strict;
use vars qw( %seen @dups );
use Getopt::Std;
use FS::UID qw(adminsuidsetup);
use FS::Record qw(qsearch qsearchs);
use FS::part_export;

my %allowed_types = map { $_ => 1 } qw ( sqlradius sqlradius_withdomain );

my $user = shift or die &usage;
adminsuidsetup $user;

my $export_x = shift;
my @part_export;
if ( !defined($export_x) ) {
  @part_export = qsearch('part_export', {} );
} elsif ( $export_x =~ /^(\d+)$/ ) {
  @part_export = qsearchs('part_export', { exportnum=>$1 } )
    or die "exportnum $export_x not found\n";
} else {
  @part_export = qsearch('part_export', { exporttype=>$export_x } )
    or die "no exports of type $export_x found\n";
}

@part_export = grep { $allowed_types{$_->exporttype} } @part_export
  or die "No sqlradius exports specified.";

foreach my $part_export ( @part_export ) {
  my $dbh = DBI->connect( map $part_export->option($_),
                           qw ( datasrc username password ) );

  my $sth = $dbh->prepare("SELECT id,username,groupname
                           FROM usergroup ORDER By username,groupname,id")
    or die $dbh->errstr;
  $sth->execute() or die $sth->errstr;

  @dups = (); %seen = ();
  while (my $row = $sth->fetchrow_arrayref ) {
    my ($userid, $username, $groupname) = @$row;
    unless ( exists($seen{$username}{$groupname}) ) {
      $seen{$username}{$groupname} = $userid;
      next;
    }
    push @dups, $userid;
  }

  $sth = $dbh->prepare("DELETE FROM usergroup WHERE id = ?")
    or die $dbh->errstr;

  foreach (@dups) {
    $sth->execute($_) or die $sth->errstr;
  }

}


sub usage {
  die "Usage:\n\n  freeside-sqlradius-dedup-group user [ exportnum|exporttype ]\n";
}

=head1 NAME

freeside-sqlradius-dedup-group - Command line tool to eliminate duplicate usergroup entries from radius tables

=head1 SYNOPSIS

  freeside-sqlradius-dedup-group user [ exportnum|exporttype ]

=head1 DESCRIPTION

  Removes all but one username groupname pair when duplicate entries exist
  for the specified export (selected by exportnum or exporttype) or all
  exports if none are specified.

=head1 SEE ALSO

L<freeside-reexport>, L<freeside-sqlradius-reset>, L<FS::part_export> 

=cut