#! /usr/bin/perl
#
use strict;
use warnings;

use DBI;
use Digest::MD5 qw(md5_base64);

my $dbh;
my $sth;

sub get_pw {
	open(URANDOM, "head /dev/urandom |"); 
	my $random_bytes = <URANDOM>;
	close(URANDOM);
	my $password = md5_base64($random_bytes);
	$password =~ s/\W//g;
	return $password;
}

sub ok {
	print "ok.\n";
}
sub fail {
	print "fail.\n";
}
sub no_ {
	print "no.\n";
}
sub yes {
	print "yes.\n";
}
sub msg {
	my $message = shift;
	print "$message...\t";
}

sub check_mysqld {
	msg "Check if mysqld running";

	sub do_check {
		my $msql_pid_file;
		my $mysql_package = `rpm -qf /usr/sbin/mysqld` or die "Can't find mysqld";
		$msql_pid_file = '/var/run/mysqld/mysqld.pid' if $mysql_package =~ /^mariadb-server/;
		$msql_pid_file = '/var/lib/mysql/mysqld.pid' if $mysql_package =~ /^MySQL-server/;
		return unless -e $msql_pid_file;
		open(PID, $msql_pid_file) or die "Can't open mysqld pid file";
		my $msql_pid = <PID>;
		close(PID);
		chomp($msql_pid);
		my $grep_result = `ps ax |grep "^ *$msql_pid .*/mysqld "`;
		chomp($grep_result);
		return unless $grep_result;
		return 1;
	}
	my $is_ok = do_check;
	yes if $is_ok;
	no_ unless $is_ok;
	return $is_ok;
}

my $root_passw = get_pw;
my $vargus_passw = get_pw;
my $vargus_web_passw = get_pw;

my $current_root_passw = '';

my $do_secure = 1;
if ($ARGV[0]) {
	warn "Warning! Root password provided; mysqld will not be secured";
	$current_root_passw = $ARGV[0];
	$do_secure = 0;
}


msg "Check if I am root";

if ($>) {
	fail;
	die "You must run this script as root";
} else {
	ok;
}


unless (check_mysqld) {
	msg "Try to start mysqld daemon";
	print "\n";
	`service mysqld start`;
	sleep(5);
	die "Can't start mysqld daemon" unless check_mysqld;
}

msg "Try to connect to mysql database";
if ($dbh = DBI->connect("DBI:mysql:mysql", "root", $current_root_passw)) {
	ok;
} else {
	fail;
	die "Can't connect to the mysql database as root with " . 
		($current_root_passw ? $current_root_passw : "empty") . " password";
}

my @databases;

$sth = $dbh->prepare("show databases");
$sth->execute;

while ((my $db) = $sth->fetchrow_array) {
	push(@databases, $db);
}

$sth->finish if $sth;

if ($do_secure) {
	msg "Securing mysqld";
	print "\n";

	msg "Set new root password";
	if ($dbh->do("UPDATE mysql.user SET Password=PASSWORD('$root_passw') WHERE User='root';")) {
		ok;
		msg "Save root password";
		if (open(PWD_FILE, "> /root/mysql.pwd") && print(PWD_FILE $root_passw . "\n") && close(PWD_FILE)) {
			ok;
			print "Root password saved in /root/mysql.pwd\n";
		} else {
			fail;
			print "Error saving root password, please remember it: $root_passw";
		}
	} else {
		fail;
		die "Can't set root password";
	}

	msg "Remove anonymous user";
	if ($dbh->do("DELETE FROM mysql.user WHERE User='';")) {
		ok;
	} else {
		fail;
		warn "Warning: anonymous user was not removed";
	}

	msg "Remove remote root access";
	if ($dbh->do("DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');")) {
		ok;
	} else {
		fail;
		warn "Warning: remote root access was not removed";
	}

	if (grep(/^test$/, @databases)) {
		msg "Dropping test database";
		if ($dbh->do("DROP DATABASE test;")) {
			ok;
		} else {
			fail;
			warn "Warning: test database was not dropped";
		}
	}


	msg "Removing privileges on test database";
	if ($dbh->do("DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';")) {
		ok;
	} else {
		fail;
		warn "Warning: privileges on test database was not removed";
	}
}


if (grep(/^vargus$/, @databases)) {
	msg "Vargus database detect, drop it first";
	if ($dbh->do("drop database vargus")) {
		ok;
	} else {
		fail;
		die "Can't drop old vargus database";
	}
}



msg "Create vargus database";
unless ($dbh->do("create database vargus;")) {
	fail;
	die "Can't create vargus database";
} else {
	ok;
}

msg "Change database to vargus";
if ($dbh->do("use vargus")) {
	ok;
} else {
	fail; 
	die "Can't select vargus database";
}

msg "Determine vargus rpm version";
my $rpm_version = `rpm -q vargus`;
chomp($rpm_version);
$rpm_version =~ s/-alt.*//;
if ($rpm_version) {
	ok;
} else {
	fail;
	die "Can't determine vargus rpm version";
}

msg "Create vargus tables";
do {{
	my $sql_file = "/usr/share/doc/$rpm_version/vargus.sql";
	unless (-e $sql_file) {
		fail;
		warn "Can't find vargus SQL file $sql_file";
		last;
	}
	unless (open (SQL, $sql_file)) {
		fail;
		warn "Can't open vargus SQL file $sql_file";
		last;
	}

	my @sql = <SQL>;
	close(SQL);

	unless(@sql) {
		fail;
		warn "Can't read vargus SQL file $sql_file";
		last;
	}

	my $sql = join ('', @sql);
	my @queries = split(';', $sql);


	foreach my $query (@queries) {
		$query =~ s/\n/ /g;
		$query =~ s/^ +//;
		$query =~ s/ +$//;
		next until $query;
		unless ($dbh->do($query)) {
			fail;
			print "Query: ====|$query|====\n";
			warn "Error execute vargus SQL";
			last;
		}
	}
} continue {
	ok;
}};


msg "Change passwords for vargus sql users";
if ($dbh->do("UPDATE mysql.user SET Password=PASSWORD('$vargus_passw') WHERE User='vargus';")) {
	print "user vargus ok; ";
} else {
	fail;
	warn "Can't change password for user vargus";
}

if ($dbh->do("UPDATE mysql.user SET Password=PASSWORD('$vargus_web_passw') WHERE User='webvargus';")) {
	print "user webvargus ok.\n";
} else {
	fail;
	warn "Can't change password for user webvargus";
}


msg "Reload privileges";
if ($dbh->do("FLUSH PRIVILEGES;")) {
	ok;
} else {
	fail;
}

$dbh->disconnect if $dbh;


unless (glob("/etc/vargus/[0-9][0-9]-*")) { 
	msg "Copy vargus configs";
	`/bin/cp /usr/share/doc/$rpm_version/examples/obj-style/* /etc/vargus/`;
	`/bin/rm -rf /etc/vargus/cam[1-4].camera.obj.cfg`;
	ok;
}

msg "Write SQL passwords into config files";
foreach my $config ('40-writer', '50-checker', '51-postprocess', 'events.cfg') {
	if (-e "/etc/vargus/$config") {
		`sed -i -e 's/sql-password=.*/sql-password=$vargus_passw/' /etc/vargus/$config`;
	}
}
foreach my $config ('get-archive.cfg') {
	if (-e "/etc/vargus/$config") {
		`sed -i -e 's/sql-password=.*/sql-password=$vargus_web_passw/' /etc/vargus/$config`;
	}
}
ok;

my $group_info = `grep "^vargus:.*apache2" /etc/group`;
unless ($group_info) {
	$group_info = `grep "^vargus:.*:\$" /etc/group`;
	my $comma = $group_info ? '' : ',';
	msg "Add apache user to the vargus group";
	`sed -r -i -e 's/\(^vargus:.*\)/\\1${comma}apache2/' /etc/group`;
	ok;
}

msg "Set apache and mysqld daemons autostart";
`chkconfig httpd2 on`;
`chkconfig mysqld on`;
ok;

msg "Restart apache daemon";
`service httpd2 restart`;
ok;

msg "Restart vargus services";
`systemctl --system daemon-reload`;
`service vargus-informer condrestart`;
`service vargus-events condrestart`;
`service vargus condrestart`;
ok;

if (-e "/home/video" && ! -d "/home/video") {
	die "/home/video is not a directory";
}

unless (-d "/home/video") {
	msg "Create directory for video: /home/video";
	if (mkdir("/home/video")) {
		ok;
	} else {
		fail;
		die "Can't create video directory /home/video";
	}
}	

my $vargus_uid = (getpwnam("vargus"))[2];

msg "Set /home/video ownership to vargus";
if (chown $vargus_uid, 0, "/home/video") {
	ok;
} else {
	fail;
}

