#!/usr/bin/perl -w
# $Id$
# Dieses Script (coldformix-sqlroot) wurde von Rdiger Beck erstellt
# Es ist freie Software
# Bei Fehlern wenden Sie sich bitte an mich.
# jeffbeck@web.de  oder  jeffbeck@gmx.de

# Bibliotheken
use strict;
use DBI;
use Getopt::Long;
Getopt::Long::Configure ("bundling");
use File::Find;
use coldformix;
# ==========================================================================

# Choose the Language: de, en
my $lang="de";

# Choose the Unit-System: si_symbol,
my $unit_system = "si_symbol";

# password for user -coldformix
my $coldformix_pass="coldformix";

my $show=0;
my $set_root_pwd=0;
my $dbh;
my $dbh2;
my $sth;
my $sql;

# sql load file is in the checked from cvs tree
# package installation script loads file from package 
my $sql_load_file="../coldformix-source/data/database/coldformix.sql";

# ===========================================================================
# Optionen verarbeiten
# ==========================================================================
# Parsen der Optionen
my $testopt=GetOptions(
           "lang|l=s" => \$lang,
           "sql-load-file|f=s" => \$sql_load_file,
           "unit_system|u=s" => \$unit_system,
           "show|s" => \$show
          );


print "Language: $lang \n";
print "Unit_System: $unit_system \n";

# Prfen, ob Optionen erkannt wurden, sonst Abbruch
&coldformix::check_options($testopt);

# check if file exists
if (not -e $sql_load_file){
    print "\nFile $sql_load_file not found\n";
    print "If you're runnning th script frmo within cvs tree,\n";
    print "be sure to be in the directory coldformix-scripts\n\n";
    exit;   
}

print "\nThis script talks about 3 passwords:\n"; 
print "    root:             mysql root user \n"; 
print "    coldformixroot:   coldformix database user (Read/Write)\n"; 
print "    coldformix:       coldformix database user (ReadOnly, Password: $coldformix_pass)\n\n"; 

# check if I can connect without password
print "\nChecking if you have a password set for root (mysql root user) ...\n"; 
    $dbh = DBI->connect("dbi:mysql:mysql", "root","",
                   { RaiseError => 0, PrintError => 0, AutoCommit => 1 });

if (defined $dbh){
    $dbh->disconnect;
    $set_root_pwd=1;
    &print_warning();
} else {
    print "   ... Password is set for root. Looks good!\n\n";
}


my $user_antwort="";
# set given password as root if necessary
if ($set_root_pwd==1){
    $user_antwort=&get_password("Which password do you want to set for root (mysql root user)?:","-->:");
    my $command="mysqladmin -u root -h localhost password $user_antwort";
    # print "$command\n";
    print "   ... setting password for mysql root user\n";
    system("$command");
} else {
    $user_antwort=&get_password("Password of user root (mysql root user):","-->:");
}


# is it the root password
$dbh = DBI->connect("dbi:mysql:mysql", "root",$user_antwort,
              { RaiseError => 0, PrintError => 0, AutoCommit => 1 });

# does the coldformix database exist?
$dbh2 = DBI->connect("dbi:mysql:coldformix", "root",$user_antwort,
              { RaiseError => 0, PrintError => 0, AutoCommit => 1 });

if (defined $dbh and defined $dbh2){
    # root password given, db exists
    print "\nI am the user root now!\n\n";
    print "The database coldformix exist already!\n";
    my $answer=&get_password("Shall I drop the database and recreate it with 2 users?","yes/no:");
    if ($answer eq "yes" or
        $answer eq "y"){
         # drop stuff
         &drop_coldformix_stuff();
         # create stuff
         &create_coldformix_stuff();
    } else {
         # dont create stuff
         exit;
    }
} elsif ($dbh and not defined $dbh2) {
    print "\nI am the user root now!\n\n";
    print "The database coldformix does not exist!\n";
    my $answer=&get_password("Shall I create the database coldformix for you with 2 users?","yes/no:");
    if ($answer eq "yes" or
        $answer eq "y"){
         # create stuff
         &create_coldformix_stuff();
    } else {
         # dont create stuff
         exit;
    }
} else {
    print "\n   ... connection failed.\n\n";
    print "Your password does not match the password of root\n\n";
    exit;
}






############################################################
# sub
############################################################

sub print_warning {
    print '
######################################################################
#                          !!  WARNING !!                            #
#   I could connect to your mysql server as root WITHOUT passwort!   #
#                    This is a security risk!                        #
#      I will set the password you provide as the root password      #
#                       (i. e. mysql root user)                      #
######################################################################
';
}


sub drop_coldformix_stuff {       
        # drop database
        print "   ... dropping database coldformix\n";
        $sth = $dbh->prepare("DROP DATABASE coldformix");
        $sth->execute();

        # drop user coldformixroot
        print "   ... dropping user coldformixroot\n";
        $sql="DROP USER coldformixroot".'@'."localhost";
        $sth = $dbh->prepare($sql);
        $sth->execute();

        # drop user coldformix
        print "   ... dropping USER coldformix\n";
        $sql="DROP USER coldformix".'@'."localhost";
        $sth = $dbh->prepare($sql);
        $sth->execute();
}



sub create_coldformix_stuff {       
        # create database
        print "   ... creating database coldformix\n";
        $sth = $dbh->prepare("CREATE DATABASE coldformix");
        $sth->execute();


        # user coldformixroot  
        my $pass_root=&get_password("Give me a password for the user coldformixroot (RW-Access):","-->:");
        if ($pass_root ne ""){
            print "   ... creating user coldformixroot\n";
            $sql="GRANT ALL ON coldformix.* TO coldformixroot".'@'.
                 "localhost IDENTIFIED BY '$pass_root'";
            # print "$sql \n";
            $sth = $dbh->prepare($sql);
            $sth->execute();
	} else {
            print "Will not create user with empty password.\n";
            exit;
        }

        # user coldformix
        print "   ... creating user coldformix with password $coldformix_pass\n";
        $sql="GRANT SELECT ON coldformix.* TO coldformix".'@'.
             "localhost IDENTIFIED BY '$coldformix_pass'";
        # print "$sql \n";
        $sth = $dbh->prepare($sql);
        $sth->execute();

        $sql="FLUSH PRIVILEGES";
        $sth = $dbh->prepare($sql);
        $sth->execute();

        print "\n";

        # fill database
        print "   ... loading database with $sql_load_file\n";
        system("mysql -u coldformixroot --password=$pass_root coldformix < $sql_load_file");
        print "   ... done\n\n";

}



sub get_password {
    my ($string,$prompt) = @_;
    my $password="";
    print "\n",$string,"\n",$prompt;
    while(){# Endlosschleife fr die Eingabe
        $password= <STDIN>; # Lesen von Tastatur
        chomp($password); # Newline abschneiden
        if ($password eq ""){
            last;
        } else {
            #last;  
        }
        print "\n";
        return $password;
    }
}
