fix spacing, braces, quotes

This commit is contained in:
Isaac Connor 2017-06-07 15:28:31 -04:00
parent a9ebcd6e8a
commit c55814647c
1 changed files with 246 additions and 251 deletions

View File

@ -55,6 +55,7 @@ a sql file, which can then be easily imported to another zoneminder system.
--help - Print usage information. --help - Print usage information.
--user=<dbuser> - Alternate dB user with privileges to alter dB. --user=<dbuser> - Alternate dB user with privileges to alter dB.
--pass=<dbpass> - Password of alternate dB user with privileges to alter dB. --pass=<dbpass> - Password of alternate dB user with privileges to alter dB.
--version - Print version.
=cut =cut
use strict; use strict;
@ -105,43 +106,43 @@ $Config{ZM_DB_USER} = $dbUser;
$Config{ZM_DB_PASS} = $dbPass; $Config{ZM_DB_PASS} = $dbPass;
if ( $version ) { if ( $version ) {
print( ZoneMinder::Base::ZM_VERSION . "\n"); print( ZoneMinder::Base::ZM_VERSION . "\n");
exit(0); exit(0);
} }
# Check to make sure commandline params make sense # Check to make sure commandline params make sense
if ( ((!$help) && ($import + $export + $topreset) != 1 )) { if ( ((!$help) && ($import + $export + $topreset) != 1 )) {
print( STDERR qq/Please give only one of the following: "import", "export", or "topreset".\n/ ); print( STDERR qq/Please give only one of the following: "import", "export", or "topreset".\n/ );
pod2usage(-exitstatus => -1); pod2usage(-exitstatus => -1);
} }
if ( ($export)&&($overwrite) ) { if ( ($export)&&($overwrite) ) {
print( "Warning: Overwrite parameter ignored during an export.\n"); print( "Warning: Overwrite parameter ignored during an export.\n");
} }
if ( ($noregex)&&(!$topreset) ) { if ( ($noregex)&&(!$topreset) ) {
print( qq/Warning: Noregex parameter only applies when "topreset" parameter is also set. Ignoring.\n/); print( qq/Warning: Noregex parameter only applies when "topreset" parameter is also set. Ignoring.\n/);
} }
if ( ($topreset)&&($ARGV[0] !~ /\d\d*/) ) { if ( ($topreset)&&($ARGV[0] !~ /\d\d*/) ) {
print( STDERR qq/Parameter "topreset" requires a valid monitor ID.\n/ ); print( STDERR qq/Parameter "topreset" requires a valid monitor ID.\n/ );
pod2usage(-exitstatus => -1); pod2usage(-exitstatus => -1);
} }
# Call the appropriate subroutine based on the params given on the commandline # Call the appropriate subroutine based on the params given on the commandline
if ($help) { if ($help) {
pod2usage(-exitstatus => -1); pod2usage(-exitstatus => -1);
} }
if ($export) { if ($export) {
exportsql(); exportsql();
} }
if ($import) { if ($import) {
importsql(); importsql();
} }
if ($topreset) { if ($topreset) {
toPreset(); toPreset();
} }
############### ###############
@ -149,299 +150,293 @@ if ($topreset) {
############### ###############
# Execute a pre-built sql select query # Execute a pre-built sql select query
sub selectQuery sub selectQuery {
{ my $dbh = shift;
my $dbh = shift; my $sql = shift;
my $sql = shift; my $monitorid = shift;
my $monitorid = shift;
my $sth = $dbh->prepare_cached( $sql ) my $sth = $dbh->prepare_cached( $sql )
or die( "Can't prepare '$sql': ".$dbh->errstr() ); or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute($monitorid) my $res = $sth->execute($monitorid)
or die( "Can't execute: ".$sth->errstr() ); or die( "Can't execute: ".$sth->errstr() );
my @data = $sth->fetchrow_array(); my @data = $sth->fetchrow_array();
$sth->finish(); $sth->finish();
return @data; return @data;
} }
# Exectute a pre-built sql query # Exectute a pre-built sql query
sub runQuery sub runQuery {
{ my $dbh = shift;
my $dbh = shift; my $sql = shift;
my $sql = shift; my $sth = $dbh->prepare_cached( $sql )
my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
or die( "Can't prepare '$sql': ".$dbh->errstr() ); my $res = $sth->execute()
my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
or die( "Can't execute: ".$sth->errstr() ); $sth->finish();
$sth->finish();
return $res; return $res;
} }
# Build and execute a sql insert query # Build and execute a sql insert query
sub insertQuery sub insertQuery {
{ my $dbh = shift;
my $dbh = shift; my $tablename = shift;
my $tablename = shift; my @data = @_;
my @data = @_;
my $sql = "INSERT INTO $tablename VALUES (NULL," my $sql = "INSERT INTO $tablename VALUES (NULL,"
.(join ", ", ("?") x @data).")"; # Add "?" for each array element .(join ', ', ('?') x @data).')'; # Add "?" for each array element
my $sth = $dbh->prepare_cached( $sql ) my $sth = $dbh->prepare_cached( $sql )
or die( "Can't prepare '$sql': ".$dbh->errstr() ); or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute(@data) my $res = $sth->execute(@data)
or die( "Can't execute: ".$sth->errstr() ); or die( "Can't execute: ".$sth->errstr() );
$sth->finish(); $sth->finish();
return $res; return $res;
} }
# Build and execute a sql delete query # Build and execute a sql delete query
sub deleteQuery sub deleteQuery {
{ my $dbh = shift;
my $dbh = shift; my $sqltable = shift;
my $sqltable = shift; my $sqlname = shift;
my $sqlname = shift;
my $sql = "DELETE FROM $sqltable WHERE Name = ?"; my $sql = "DELETE FROM $sqltable WHERE Name = ?";
my $sth = $dbh->prepare_cached( $sql ) my $sth = $dbh->prepare_cached( $sql )
or die( "Can't prepare '$sql': ".$dbh->errstr() ); or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute($sqlname) my $res = $sth->execute($sqlname)
or die( "Can't execute: ".$sth->errstr() ); or die( "Can't execute: ".$sth->errstr() );
$sth->finish(); $sth->finish();
return $res; return $res;
} }
# Build and execute a sql select count query # Build and execute a sql select count query
sub checkExists sub checkExists {
{ my $dbh = shift;
my $dbh = shift; my $sqltable = shift;
my $sqltable = shift; my $sqlname = shift;
my $sqlname = shift; my $result = 0;
my $result = 0;
my $sql = "SELECT count(*) FROM $sqltable WHERE Name = ?"; my $sql = "SELECT count(*) FROM $sqltable WHERE Name = ?";
my $sth = $dbh->prepare_cached( $sql ) my $sth = $dbh->prepare_cached( $sql )
or die( "Can't prepare '$sql': ".$dbh->errstr() ); or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute($sqlname) my $res = $sth->execute($sqlname)
or die( "Can't execute: ".$sth->errstr() ); or die( "Can't execute: ".$sth->errstr() );
my $rows = $sth->fetchrow_arrayref(); my $rows = $sth->fetchrow_arrayref();
$sth->finish(); $sth->finish();
if ($rows->[0] > 0) { if ($rows->[0] > 0) {
$result = 1; $result = 1;
} }
return $result; return $result;
} }
# Import camera control & presets into the zoneminder dB # Import camera control & presets into the zoneminder dB
sub importsql sub importsql {
{ my @newcontrols;
my @newcontrols; my @overwritecontrols;
my @overwritecontrols; my @skippedcontrols;
my @skippedcontrols; my @newpresets;
my @newpresets; my @overwritepresets;
my @overwritepresets; my @skippedpresets;
my @skippedpresets; my %controls;
my %controls; my %monitorpresets;
my %monitorpresets;
if ($ARGV[0]) { if ($ARGV[0]) {
$sqlfile = $ARGV[0]; $sqlfile = $ARGV[0];
} else {
$sqlfile = $Config{ZM_PATH_DATA}.'/db/zm_create.sql';
}
open(my $SQLFILE,'<',$sqlfile)
or die( "Can't Open file: $!\n" );
# Find and extract ptz control and monitor preset records
while (<$SQLFILE>) {
# Our regex replaces the primary key with NULL
if (s/^(INSERT INTO .*?Controls.*? VALUES \().*?(,')(.*?)(',.*)/$1NULL$2$3$4/i) {
$controls{$3} = $_;
} elsif (s/^(INSERT INTO .*?MonitorPresets.*? VALUES \().*?(,')(.*?)(',.*)/$1NULL$2$3$4/i) {
$monitorpresets{$3} = $_;
}
}
close $SQLFILE;
if ( ! (%controls || %monitorpresets) ) {
die( "Error: No relevant data found in $sqlfile.\n" );
}
# Now that we've got what we were looking for,
# compare to what is already in the dB
my $dbh = zmDbConnect();
foreach (keys %controls) {
if (!checkExists($dbh,'Controls',$_)) {
# No existing Control was found. Add new control to dB.
runQuery($dbh,$controls{$_});
push @newcontrols, $_;
} elsif ($overwrite) {
# An existing Control was found and the overwrite flag is set.
# Overwrite the control.
deleteQuery($dbh,'Controls',$_);
runQuery($dbh,$controls{$_});
push @overwritecontrols, $_;
} else { } else {
$sqlfile = $Config{ZM_PATH_DATA}.'/db/zm_create.sql'; # An existing Control was found and the overwrite flag was not set.
# Do nothing.
push @skippedcontrols, $_;
} }
}
open(my $SQLFILE,"<",$sqlfile) foreach (keys %monitorpresets) {
or die( "Can't Open file: $!\n" ); if (!checkExists($dbh,'MonitorPresets',$_)) {
# No existing MonitorPreset was found. Add new MonitorPreset to dB.
runQuery($dbh,$monitorpresets{$_});
push @newpresets, $_;
} elsif ($overwrite) {
# An existing MonitorPreset was found and the overwrite flag is set.
# Overwrite the MonitorPreset.
deleteQuery($dbh,'MonitorPresets',$_);
runQuery($dbh,$monitorpresets{$_});
push @overwritepresets, $_;
} else {
# An existing MonitorPreset was found and the overwrite flag was
# not set. Do nothing.
push @skippedpresets, $_;
}
}
# Find and extract ptz control and monitor preset records if (@newcontrols) {
while (<$SQLFILE>) { print 'Number of ptz camera controls added: '
# Our regex replaces the primary key with NULL .scalar(@newcontrols)."\n";
if (s/^(INSERT INTO .*?Controls.*? VALUES \().*?(,')(.*?)(',.*)/$1NULL$2$3$4/i) { }
$controls{$3} = $_; if (@overwritecontrols) {
} elsif (s/^(INSERT INTO .*?MonitorPresets.*? VALUES \().*?(,')(.*?)(',.*)/$1NULL$2$3$4/i) { print 'Number of existing ptz camera controls overwritten: '
$monitorpresets{$3} = $_; .scalar(@overwritecontrols)."\n";
} }
} if (@skippedcontrols) {
close $SQLFILE; print 'Number of existing ptz camera controls skipped: '
.scalar(@skippedcontrols)."\n";
}
if ( ! (%controls || %monitorpresets) ) { if (@newpresets) {
die( "Error: No relevant data found in $sqlfile.\n" ); print 'Number of monitor presets added: '
} .scalar(@newpresets)."\n";
}
# Now that we've got what we were looking for, if (@overwritepresets) {
# compare to what is already in the dB print 'Number of existing monitor presets overwritten: '
.scalar(@overwritepresets)."\n";
my $dbh = zmDbConnect(); }
foreach (keys %controls) { if (@skippedpresets) {
if (!checkExists($dbh,"Controls",$_)) { print 'Number of existing presets skipped: '
# No existing Control was found. Add new control to dB. .scalar(@skippedpresets)."\n";
runQuery($dbh,$controls{$_}); }
push @newcontrols, $_;
} elsif ($overwrite) {
# An existing Control was found and the overwrite flag is set.
# Overwrite the control.
deleteQuery($dbh,"Controls",$_);
runQuery($dbh,$controls{$_});
push @overwritecontrols, $_;
} else {
# An existing Control was found and the overwrite flag was not set.
# Do nothing.
push @skippedcontrols, $_;
}
}
foreach (keys %monitorpresets) {
if (!checkExists($dbh,"MonitorPresets",$_)) {
# No existing MonitorPreset was found. Add new MonitorPreset to dB.
runQuery($dbh,$monitorpresets{$_});
push @newpresets, $_;
} elsif ($overwrite) {
# An existing MonitorPreset was found and the overwrite flag is set.
# Overwrite the MonitorPreset.
deleteQuery($dbh,"MonitorPresets",$_);
runQuery($dbh,$monitorpresets{$_});
push @overwritepresets, $_;
} else {
# An existing MonitorPreset was found and the overwrite flag was
# not set. Do nothing.
push @skippedpresets, $_;
}
}
if (@newcontrols) {
print "Number of ptz camera controls added: "
.scalar(@newcontrols)."\n";
}
if (@overwritecontrols) {
print "Number of existing ptz camera controls overwritten: "
.scalar(@overwritecontrols)."\n";
}
if (@skippedcontrols) {
print "Number of existing ptz camera controls skipped: "
.scalar(@skippedcontrols)."\n";
}
if (@newpresets) {
print "Number of monitor presets added: "
.scalar(@newpresets)."\n";
}
if (@overwritepresets) {
print "Number of existing monitor presets overwritten: "
.scalar(@overwritepresets)."\n";
}
if (@skippedpresets) {
print "Number of existing presets skipped: "
.scalar(@skippedpresets)."\n";
}
} }
# Export camera controls & presets from the zoneminder dB to STDOUT # Export camera controls & presets from the zoneminder dB to STDOUT
sub exportsql sub exportsql {
{
my ( $host, $port ) = ( $Config{ZM_DB_HOST} =~ /^([^:]+)(?::(.+))?$/ ); my ( $host, $port ) = ( $Config{ZM_DB_HOST} =~ /^([^:]+)(?::(.+))?$/ );
my $command = "mysqldump -t --skip-opt --compact -h".$host; my $command = 'mysqldump -t --skip-opt --compact -h'.$host;
$command .= " -P".$port if defined($port); $command .= ' -P'.$port if defined($port);
if ( $dbUser ) { if ( $dbUser ) {
$command .= " -u".$dbUser; $command .= ' -u'.$dbUser;
if ( $dbPass ) { if ( $dbPass ) {
$command .= " -p".$dbPass; $command .= ' -p'.$dbPass;
}
} }
}
if ($ARGV[0]) { if ($ARGV[0]) {
$command .= qq( --where="Name = '$ARGV[0]'"); $command .= qq( --where="Name = '$ARGV[0]'");
} }
$command .= " zm Controls MonitorPresets"; $command .= " zm Controls MonitorPresets";
my $output = qx($command); my $output = qx($command);
my $status = $? >> 8; my $status = $? >> 8;
if ( $status || logDebugging() ) { if ( $status || logDebugging() ) {
chomp( $output ); chomp( $output );
print( "Output: $output\n" ); print( "Output: $output\n" );
} }
if ( $status ) { if ( $status ) {
die( "Command '$command' exited with status: $status\n" ); die( "Command '$command' exited with status: $status\n" );
} else { } else {
# NULLify the primary keys before printing the output to STDOUT # NULLify the primary keys before printing the output to STDOUT
$output =~ s/VALUES \((.*?),'/VALUES \(NULL,'/ig; $output =~ s/VALUES \((.*?),'/VALUES \(NULL,'/ig;
print $output; print $output;
} }
} }
sub toPreset sub toPreset {
{ my $dbh = zmDbConnect();
my $dbh = zmDbConnect(); my $monitorid = $ARGV[0];
my $monitorid = $ARGV[0];
# Grap the following fields from the Monitors table # Grap the following fields from the Monitors table
my $sql = "SELECT my $sql = 'SELECT
Name, Name,
Type, Type,
Device, Device,
Channel, Channel,
Format, Format,
Protocol, Protocol,
Method, Method,
Host, Host,
Port, Port,
Path, Path,
SubPath, SubPath,
Width, Width,
Height, Height,
Palette, Palette,
MaxFPS, MaxFPS,
Controllable, Controllable,
ControlId, ControlId,
ControlDevice, ControlDevice,
ControlAddress, ControlAddress,
DefaultRate, DefaultRate,
DefaultScale DefaultScale
FROM Monitors WHERE Id = ?"; FROM Monitors WHERE Id = ?';
my @data = selectQuery($dbh,$sql,$monitorid); my @data = selectQuery($dbh,$sql,$monitorid);
if (!@data) { if (!@data) {
die( "Error: Monitor Id $monitorid does not appear to exist in the database.\n" ); die( "Error: Monitor Id $monitorid does not appear to exist in the database.\n" );
}
# Attempt to search for and replace system specific values such as
# ip addresses, ports, usernames, etc. with generic placeholders
if (!$noregex) {
foreach (@data) {
next if ! $_;
s/\b(?:\d{1,3}\.){3}\d{1,3}\b/<ip-address>/; # ip address
s/<ip-address>:(6553[0-5]|655[0-2]\d|65[0-4]\d\d|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)$/<ip-address>:<port>/; # tcpip port
s/\/\/.*:.*@/\/\/<username>:<pwd>@/; # user & pwd preceding an ip address
s/(&|\?)(user|username)=\w\w*(&|\?)/$1$2=<username>$3/i; # username embedded in url
s/(&|\?)(pwd|password)=\w\w*(&|\?)/$1$2=<pwd>$3/i; # password embedded in url
s/\w\w*:\w\w*/<username>:<pwd>/; # user & pwd in their own field
s/\/dev\/video\d\d*/\/dev\/video<?>/; # local video devices
} }
}
# Attempt to search for and replace system specific values such as if (!checkExists($dbh,"MonitorPresets",$data[0])) {
# ip addresses, ports, usernames, etc. with generic placeholders # No existing Preset was found. Add new Preset to dB.
if (!$noregex) { print "Adding new preset: $data[0]\n";
foreach (@data) { insertQuery($dbh,'MonitorPresets',@data);
next if ! $_; } elsif ($overwrite) {
s/\b(?:\d{1,3}\.){3}\d{1,3}\b/<ip-address>/; # ip address # An existing Control was found and the overwrite flag is set.
s/<ip-address>:(6553[0-5]|655[0-2]\d|65[0-4]\d\d|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)$/<ip-address>:<port>/; # tcpip port # Overwrite the control.
s/\/\/.*:.*@/\/\/<username>:<pwd>@/; # user & pwd preceding an ip address print "Existing preset $data[0] detected.\nOverwriting...\n";
s/(&|\?)(user|username)=\w\w*(&|\?)/$1$2=<username>$3/i; # username embedded in url deleteQuery($dbh,'MonitorPresets',$data[0]);
s/(&|\?)(pwd|password)=\w\w*(&|\?)/$1$2=<pwd>$3/i; # password embedded in url insertQuery($dbh,'MonitorPresets',@data);
s/\w\w*:\w\w*/<username>:<pwd>/; # user & pwd in their own field } else {
s/\/dev\/video\d\d*/\/dev\/video<?>/; # local video devices # An existing Control was found and the overwrite flag was not set.
} # Do nothing.
} print "Existing preset $data[0] detected and overwrite flag not set.\nSkipping...\n";
}
if (!checkExists($dbh,"MonitorPresets",$data[0])) {
# No existing Preset was found. Add new Preset to dB.
print "Adding new preset: $data[0]\n";
insertQuery($dbh,"MonitorPresets",@data);
} elsif ($overwrite) {
# An existing Control was found and the overwrite flag is set.
# Overwrite the control.
print "Existing preset $data[0] detected.\nOverwriting...\n";
deleteQuery($dbh,"MonitorPresets",$data[0]);
insertQuery($dbh,"MonitorPresets",@data);
} else {
# An existing Control was found and the overwrite flag was not set.
# Do nothing.
print "Existing preset $data[0] detected and overwrite flag not set.\nSkipping...\n";
}
} }
1;
__END__