#!/bin/bash

# Test package that computes default database settings

TMP_DIR="${TMPDIR}"

test -z "${LIB_DIR}" && LIB_DIR=lib

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

BASENAME=$(basename $0 .pm)

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

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

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

set -ue
## set -x

test -z "${TMP_DIR}" && TMP_DIR="/tmp"
TMP_DIR="${TMP_DIR}/tmp-${BASENAME}-$$"
mkdir "${TMP_DIR}"

# To make the trap portable between bash and dash, we need to trap
# "signal" 0 ("EXIT") and rely on it for the cleanup:
## trap "rm -rf '${TMP_DIR}'" 0 1 2 3 15
trap "rm -rf '${TMP_DIR}'" EXIT
trap "exit 1" HUP INT QUIT TERM

TMP_DB_MAIN="${TMP_DIR}/test4fk.db"
TMP_DB_META="${TMP_DIR}/restful.db"

cp db/test4fk.db ${TMP_DB_MAIN}
cp db/restful.db ${TMP_DB_META}

sqlite3 ${TMP_DB_META} "delete from db_users"
sqlite3 ${TMP_DB_META} "insert into db_users (id, db_username, username_hash) values (1, 'New Alice Name','3bc51062973c458d5a6f2d8d64a023246354ad7e064b1e4e009ec8a0699a3043')"

export TMP_DB_MAIN

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

use strict;
use warnings;
use utf8;

use lib 'lib';
use Database;

binmode( STDOUT, "utf8" );

my $db_settings = {
    content_db => {
        DB => $ENV{TMP_DB_MAIN},
        engine => 'SQLite',            
        user => 'Alice'
    }
};

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

print $db->{db}{content}{user};

END

# Temporary directory will be deleted by the trap.
