#!/usr/bin/perl

use strict;

my $arg = shift @ARGV || die "please specify a service or db";
my $command = join (' ',@ARGV);
my $out;

# did user specify a service name?
chomp($out = `find /dh/mysql/ -maxdepth 1 -mindepth 1 -name $arg`);
if ($out) {
	my @tokens = split /\//, $out;
	my $service = $tokens[3];
	unless ($service eq $arg) { die "something not right here\n"; }

	$out = `grep 'backup pass' /dh/mysql/$service/my.cnf`;
	@tokens = split /\s+/, $out;
	my $pass = $tokens[4];
	
	$command =~ s/'/\\'/g if ($command);
	my $cmd = "mysql -A -u root -p\'$pass\' -S /dh/mysql/$service/mysql.$service.sock";
	$cmd .= " -e '$command'" if ($command);

	# print "$cmd\n";
	system "$cmd";
	exit 0;
}

# did user specify a database name instead?
chomp($out = `find /dh/mysql/ -maxdepth 3 -mindepth 3 -name $arg`);
if ($out) {
	my $db = $arg;
	my @tokens = split /\//, $out;
	my $service = $tokens[3];
	
	$out = `grep 'backup pass' /dh/mysql/$service/my.cnf`;
	@tokens = split /\s+/, $out;
	my $pass = $tokens[4];
	
	$command =~ s/'/\\'/g if ($command);
	my $cmd = "mysql -A -u root -p\'$pass\' -S /dh/mysql/$service/mysql.$service.sock $db";
	$cmd .= " -e '$command'" if ($command);

	# print "$cmd\n";
	system "$cmd";
	exit 0;
}



