#!/bin/bash
#set -x


#REPOFLAGS=7 # Sobrescribe host, port, url, dbname, usuario y clave
REPOFLAGS=2 # Sobrescribe usuario y clave

StoresRepositoryId="sample"
StoresRepositoryLabel="Sample"

if [[ "${1}" == "-?" || "${1}" == "-h" || "${1}" == "--help" ]] ; then
  echo "Usage: 
  gvsigdtables [folder]
    Where folder or current directory is a local resources folder for a database connection.

    Create SQL (pg) for the local resources folder of the database connection.
"
  exit 1
fi
if [[ "${1}" == "" ]] ; then
    WORKDIR="$(realpath -- "$PWD")"
    if [[ ! -d "$WORKDIR/repository" && ! -d "$WORKDIR/resources" ]] ; then
        echo "Current directory is not a local resources folder for a database connection."
        echo "Usage: 
  gvsigdtables [folder]
    Where folder or current directory is a local resources folder for a database connection.

    Create SQL (pg) for the local resources folder of the database connection.
"
        exit 1
    fi
else
    WORKDIR="$(realpath -- "$1")"
    if [[ ! -d "$WORKDIR/repository" && ! -d "$WORKDIR/resources" ]] ; then
        echo "Parameter is not a local resources folder for a database connection."
        echo "Usage: 
  gvsigdtables [folder]
    Where folder or current directory is a local resources folder for a database connection.

    Create SQL (pg) for the local resources folder of the database connection.
"
        exit 2
    fi
fi
type hexdump >/dev/null
#type xxd >/dev/null
if [[ "$?" != "0" ]] ; then
    echo "Command 'hexdump' not found."
    exit 3
fi
cd "$WORKDIR"


cat <<EOFCAT

CREATE TABLE IF NOT EXISTS public."GVSIGD_CONFIG"
(
    name character varying(200) NOT NULL,
    value text,
    CONSTRAINT "GVSIGD_CONFIG_pkey" PRIMARY KEY (name)
);

CREATE TABLE IF NOT EXISTS public."GVSIGD_REPOSITORY"
(
    name character varying(150) NOT NULL,
    parameters bytea,
    flags integer NOT NULL DEFAULT 0,
    extra text,
    CONSTRAINT "GVSIGD_REPOSITORY_pkey" PRIMARY KEY (name)
);

CREATE TABLE IF NOT EXISTS public."GVSIGD_RESOURCES"
(
    name character varying(150) NOT NULL,
    resource bytea,
    CONSTRAINT "GVSIGD_RESOURCES_pkey" PRIMARY KEY (name)
);

INSERT INTO public."GVSIGD_CONFIG"(name, value) VALUES ('StoresRepository.id','${StoresRepositoryId}') 
    ON CONFLICT(name) 
    DO UPDATE SET value = EXCLUDED.value;

INSERT INTO public."GVSIGD_CONFIG"(name, value) VALUES ('StoresRepository.label','${StoresRepositoryLabel}')
    ON CONFLICT(name) 
    DO UPDATE SET value = EXCLUDED.value;

EOFCAT

cd "$WORKDIR/repository"

for PATHNAME in * 
do
    if [[ -f "$PATHNAME" ]] ; then
        EXT="${PATHNAME/*./}"
        if [[ "$EXT" == "table" ]] ; then
            NAME="${PATHNAME/.*/}"
            CONTENT=$(unzip -qc $PATHNAME state.xml)
            if [[ "$REPOFLAGS" == 7 ]] ; then
                CONTENT="${CONTENT/host type=\"string\">*<\/host>/host type=\"string\">DBHOST<\/host>}"
                #CONTENT="${CONTENT/port type=\"integer\">*<\/port>/port type=\"integer\">5432<\/port>}"
                CONTENT="${CONTENT/dbname type=\"string\">*<\/dbname>/dbname type=\"string\">DBNAME<\/dbname>}"
                CONTENT="${CONTENT/dbuser type=\"string\">*<\/dbuser>/dbuser type=\"string\">DBUSER<\/dbuser>}"
                CONTENT="${CONTENT/password type=\"string\">*<\/password>/password type=\"string\">DBPASS<\/password>}"
            elif [[ "$REPOFLAGS" == 2 ]] ; then
                CONTENT="${CONTENT/dbuser type=\"string\">*<\/dbuser>/dbuser type=\"string\">DBUSER<\/dbuser>}"
                CONTENT="${CONTENT/password type=\"string\">*<\/password>/password type=\"string\">DBPASS<\/password>}"
            fi 
            EXTRA=""
            if [[ -f "${NAME}.props" ]] ; then
                EXTRA=$(cat "${NAME}.props")
            fi
            echo "INSERT INTO public.\"GVSIGD_REPOSITORY\" (name,parameters,flags, extra) VALUES (
'${NAME}',
\$\$${CONTENT}\$\$,
${REPOFLAGS},
\$\$${EXTRA}\$\$
)
ON CONFLICT(name) 
DO UPDATE SET
  parameters = EXCLUDED.parameters,
  flags = EXCLUDED.flags,
  extra = EXCLUDED.extra;

"
        fi
    fi
done

cd "$WORKDIR"

for PATHNAME in resources/*/* 
do
    RESNAME="$(basename "$PATHNAME")"

    X=$(dirname -- $PATHNAME)
    TABLENAME=$(basename -- $X)

    #CONTENTS=$(xxd -plain ${PATHNAME} | tr -d '\n')
    CONTENTS=$(hexdump -v -e '/1 "%02X"' ${PATHNAME})

    echo "INSERT INTO public.\"GVSIGD_RESOURCES\" (name,resource) VALUES (
  '${TABLENAME}.${RESNAME}',
  decode(
    '${CONTENTS}',
    'hex'
  )
)
ON CONFLICT(name) 
DO UPDATE SET
  resource = EXCLUDED.resource;

"
done

