#!/usr/bin/perl

use strict;

use Sys::Hostname;
use Getopt::Std;

use lib '/app/tools/common/lib';
use Common::RSDB;

my %opt;
getopts( 'h:u', \%opt );

die usage() if $opt{t};

my $HOST = $opt{h} || hostname();
$HOST = lc $HOST;
$HOST =~ s/^(.+?)\..*$/$1/;
$HOST = '' if ( $HOST eq '*' );

my $CMD = 'mysql -uroot';

if ( defined $ARGV[0] ) {
    if ( $ARGV[0] =~ /^\d+$/ ) {
        connect_by_id( $ARGV[0] );
        exit();
    } elsif ( $ARGV[0] =~ m/^\w+$/i ) {
        my @match = ();
        foreach my $id ( keys %Common::RSDB::CLIENT_DB ) {
            next if ( $HOST and $Common::RSDB::CLIENT_DB{$id}{host_id} !~ /$HOST/ );
            push( @match, $id ) if ( $Common::RSDB::CLIENT_DB{$id}{db_name} =~ /^c_$ARGV[0]/i );
        }

        if ( scalar @match == 1 ) {
            connect_by_id( $match[0] );
            exit();
        } elsif (@match) {
            show_list(@match);
            exit();
        }
    }
}

# no match above or no argv[0]
show_list( sort_order() );

#/////////////////////////////////////////////////

sub connect_by_id {
    my $id = shift;
    chomp($id);

    die "\nunknown id\n" unless ( exists $Common::RSDB::CLIENT_DB{$id} );
    print "\nconnecting to $Common::RSDB::CLIENT_DB{$id}{db_name}\n\n";

    my $CMD = sprintf(
        "mysql -u%s -p%s -h%s %s",
        $Common::RSDB::CLIENT_DB{$id}{username}, $Common::RSDB::CLIENT_DB{$id}{password},
        $Common::RSDB::CLIENT_DB{$id}{server},   $Common::RSDB::CLIENT_DB{$id}{db_name}
    );
    print "CMD: $CMD\n";
    system("$CMD");
}

sub show_list {
    my @idList = @_;
    unless (@idList) {
        print "no matching db's\n";
        usage();
        return undef;
    }

    map {
        print "$_\t$Common::RSDB::CLIENT_DB{$_}{db_name} ($Common::RSDB::CLIENT_DB{$_}{host_id})\n"
          if ( $Common::RSDB::CLIENT_DB{$_}{db_name} =~ /^(C_|RS)/ )
    } @idList;

    print "\nchoice: ";
    my $id = <STDIN>;

    connect_by_id($id);
}

sub sort_order {
    my @full_list =
      sort { $Common::RSDB::CLIENT_DB{$a}->{db_name} cmp $Common::RSDB::CLIENT_DB{$b}->{db_name} } keys %Common::RSDB::CLIENT_DB;

    return @full_list unless $HOST;

    my @short_list = ();
    map { push @short_list, $_ if ( $Common::RSDB::CLIENT_DB{$_}->{host_id} =~ /$HOST/ ); } @full_list;

    return @short_list;
}

sub usage {
    print <<EofUSAGE;

usage: $0 [-h host (rps or raptor) default is local hostname] [ID or first letters of db name]

examples:
$0 14 (connect to client_id 14 - dualtone)
$0 sanc (list (if multiple) or connect to (if one) client db_name starting with 'sanc')
$0 -hrps lau (same as above but only match to db's on rps*)
$0 -hrap (list all db's on host rps)
$0 -h* (list all db's on all hosts)

EofUSAGE
}
