#! /bin/sh

SCRIPT_BASE=`basename $0 | sed "s/_[0-9]*\.sh$//"`

#BEGIN DEPEND------------------------------------------------------------------

INPUT_SCRIPT="${BIN_DIR}/${SCRIPT_BASE}"

#END DEPEND--------------------------------------------------------------------

set -ue
## set -x

TMP_DB_TABLE="tmp_table_$$"

TMP_DB_NAME=$(cat tests/config/mysql.name)
TMP_DB_CONF=tests/config/mysql.cnf

export TMP_DB_NAME
export TMP_DB_TABLE

mysql --defaults-file=${TMP_DB_CONF} ${TMP_DB_NAME} <<END
    drop table if exists ${TMP_DB_TABLE};
    create table ${TMP_DB_TABLE} (
        id INTEGER PRIMARY KEY NOT NULL AUTO_INCREMENT,
        uuid CHAR(36) NOT NULL,
        SolsaID CHAR(12) NOT NULL UNIQUE
    )
END

perl <<'END'
#! /usr/bin/env perl

# Test package that computes default database settings:

use strict;
use warnings;
use utf8;
use Config::Auto;
use Data::Dumper;

use lib 'lib';
use Database;

binmode( STDOUT, "utf8" );

$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent   = 1;

my $mysql_cnf = Config::Auto::parse( 'tests/config/mysql.cnf' );

my $db_settings = {
    content_db => {
        DB       => $ENV{TMP_DB_NAME},
        engine   => 'mysql',
        user     => $mysql_cnf->{client}{user},
        password => $mysql_cnf->{client}{password},
    }
};

my $db = Database->new( $db_settings );
$db->connect();

print Dumper $db->_insert_record( { SolsaID => 'XX-TEST-0002',
                                    uuid => 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' },
                                  $ENV{TMP_DB_TABLE} );
print Dumper $db->_insert_record( { SolsaID => 'XX-TEST-0002' },
                                  $ENV{TMP_DB_TABLE},
                                  { duplicates => 'update' } );
END

mysql --defaults-file=${TMP_DB_CONF} ${TMP_DB_NAME} <<END
    select id, uuid from ${TMP_DB_TABLE} where uuid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
    drop table ${TMP_DB_TABLE};
END
