#!/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}/test.db"

sqlite3 ${TMP_DB_MAIN} "create table parent(id int, name text)"
sqlite3 ${TMP_DB_MAIN} "create table child(id int, parent_id int, FOREIGN KEY(parent_id) REFERENCES parent(id))"
sqlite3 ${TMP_DB_MAIN} "insert into parent values (1, 'first entry')"
sqlite3 ${TMP_DB_MAIN} "insert into parent values (2, 'second entry')"
sqlite3 ${TMP_DB_MAIN} "insert into child values (1, 1)"

export TMP_DB_MAIN

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

# Test package that computes default database settings:

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

use lib 'lib';
use Database;

binmode( STDOUT, "utf8" );

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

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

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

my $data = $db->get_record_descriptions( 'child', { record_id => 1 } );
print Dumper $data;
my $dom  = $db->form_parameters_to_descriptions(
    $data, { 'column:child:0.parent_id' => 2,
             'action:child:0' => 'update' }
);
print Dumper $dom;
$db->modify_record_descriptions( $dom );
END

sqlite3 -nullvalue NULL ${TMP_DB_MAIN} 'select * from child'

# Temporary directory will be deleted by the trap.
