#!/bin/bash
#set -x


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

StoresRepositoryId="sample"
StoresRepositoryLabel="Sample"
deleteResources="No"
deleteRepository="No"

help() {
  cat <<HELPEOF
Esta utilidad permite administrar los recursos locales.
Modo de empleo: gvsigdtables PARAMETERS
Los parámetros soportados son:
-I, --repoid id                     Especifica el id del repositorio usado para 
                                    inicializar la carpeta de recursos locales y 
                                    en la generación del script SQL.
-L, --repolabel label               Especifica la etiqueta del repositorio usado 
                                    para inicializar la carpeta de recursos locales 
                                    y en la generación del script SQL.
-i, --init                          Inicializa la carpeta de los recursos locales.
                                    Use --repoId --repolabel para configurar el id y 
                                    la etiqueta del repositorio
-t, --addtable table                Inicializa la carpeta de resursos asociada a la 
                                    tabla indicada.
-p, --createprops table group label Inicializa las propiedades de la tabla indicada 
                                    en el repositorio.
-m, --makesql                       Genera el script SQL asociado a los recursos locales.
                                    Use --delres o --delrepo para configurar el borrado de datos
-d, --dir folder                    Usa la carpeta indicada como carpeta de recursos locales.
                                    Si no se especifica, se utilizará la carpeta corriente. 
--delres                            Si se especifica esta opción se eliminan los datos de 
                                    la tabla GVSIGD_RESOURCES
--delrepo                           Si se especifica esta opción se eliminan los datos de 
                                    la tabla GVSIGD_REPOSITORY
-h, --help                          Muestra esta ayuda.

HELPEOF
  x="$(basename "${WORKDIR}")"
  x="${x/r-*/r-}"
  if [[ "$x" != "r-" ]] ; then
    echo "Carpeta actual"
    echo "${WORKDIR}"
    echo "La carpeta actual no es una carpeta de recurosos válida"
  fi
}

checkWorkDir() {
  x="$(basename "${WORKDIR}")"
  x="${x/r-*/r-}"
  if [[ "$x" != "r-" ]] ; then
    echo "Current directory is not valid"
    exit 2
  fi
}

createRepositoryProps() {
  tableName="$1"
  catalogGroup="$2"
  label="$3"
  if [[ ! -f "${WORKDIR}/repository/${tableName}.table" ]] ; then
    echo "No se ha encontrado el archivo con los parámetros de apertura de la tabla ${tableName}"
    echo "se esperaba encontrar ${WORKDIR}/repository/${tableName}.table"
  fi
  echo "
{
    \"catalog.group\":\"${catalogGroup}\",
    \"label\":\"${label}\"
}
">"${WORKDIR}/repository/${tableName}.props"
}

addtable() {
  checkWorkDir
  if [[ "$1" == "" ]] ; then
    exit 3
  fi
  mkdir -p "$WORKDIR/resources/$1"
}

initfolder() {
  checkWorkDir
  if [[ "${StoresRepositoryId}" == "" ]] ; then
    echo "The repository id is needed"
    exit 3
  fi
  if [[ "${StoresRepositoryLabel}" == "" ]] ; then
    StoresRepositoryLabel="${StoresRepositoryId}"
  fi
  mkdir -p "$WORKDIR/resources"
  mkdir -p "$WORKDIR/repository"
  echo "name/String/set/size=200/set/allowNull=false/set/pk=true/set/isindexed=true/set/order=10;value/String/set/size=2147483647/set/order=20
StoresRepository.id;\"${StoresRepositoryId}\"
StoresRepository.label;\"${StoresRepositoryLabel}\"
">"${WORKDIR}/config.csv"
}

generateSQLs(){
    checkWorkDir
    type hexdump >/dev/null
    #type xxd >/dev/null
    if [[ "$?" != "0" ]] ; then
        echo "Command 'hexdump' not found."
        exit 3
    fi
    cd "$WORKDIR"

    x=$(grep "StoresRepository[.]id" config.csv)
    y="${x/StoresRepository.id;\"/}"
    StoresRepositoryId=${y/\"/}

    x=$(grep "StoresRepository[.]label" config.csv)
    y="${x/StoresRepository.label;\"/}"
    StoresRepositoryLabel=${y/\"/}

    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
    if [[ "$deleteRepository" == "Si" ]] ; then
        echo 'DELETE FROM public."GVSIGD_REPOSITORY";'
    fi
    if [[ "$deleteResources" == "Si" ]] ; then
        echo 'DELETE FROM public."GVSIGD_RESOURCES";'
    fi
    cd "$WORKDIR/repository"

    for PATHNAME in * 
    do
        if [[ -f "$PATHNAME" ]] ; then
            EXT="${PATHNAME/*./}"
            if [[ "$EXT" == "table" ]] ; then
                NAME="${PATHNAME/.*/}"
                x=$(file -b $PATHNAME)
                if [[ "${x/XML*/XML}" == "XML" ]] ; then 
                    CONTENT=$(cat $PATHNAME)
                else
                    CONTENT=$(unzip -qc $PATHNAME state.xml)
                fi
                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)

        x=$(file -b --mime-type $PATHNAME)
        if [[ "${x/text\/*/text}" == "text" ]] ; then 
            CONTENTS=$(cat $PATHNAME)

            echo ${CONTENTS}|grep "\\\$\\\$" > /dev/null
            if [[ "$?" == "0" ]] ; then
                # Si contienen la cadena "$$" lo codificamos en hexadecimal
                CONTENTS=$(hexdump -v -e '/1 "%02X"' ${PATHNAME})
                CONTENTS="decode(
    '${CONTENTS}',
    'hex'
  )"
            else
                CONTENTS="convert_to(\$\$${CONTENTS}\$\$,'UTF8')"
            fi
        else
            #CONTENTS=$(xxd -plain ${PATHNAME} | tr -d '\n')
            CONTENTS=$(hexdump -v -e '/1 "%02X"' ${PATHNAME})
            CONTENTS="decode(
    '${CONTENTS}',
    'hex'
  )"
        fi

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

"
    done
}

initWorkDir() {
  x="$(realpath -- "$1")"
  if [[ $(basename "${x/r-*/r-}") != "r-" ]] ; then
    echo "The directory is not valid"
    exit 2
  fi
  WORKDIR="$x"
}

WORKDIR="$(realpath -- "$PWD")"
while [[ "$#" > 0 ]]
do
    case "${1}" in 
      "-d"|"--dir" )
        shift
        initWorkDir $1
        shift
        ;;
      "-i"|"--init" )
        shift
        initfolder
        ;;
      "-t"|"--addtable" )
        shift
        addtable $1
        shift
        ;;
      "-L"|"--repolabel" )
        shift
        StoresRepositoryLabel=$1
        shift
        ;;
      "-I"|"--repoid" )
        shift
        StoresRepositoryId=$1
        shift
        ;;
      "-p"|"--createprops" )
        shift
        createRepositoryProps "$1" "$2" "$3"
        shift 3
        ;;
      "--delrepo" )
        shift
        deleteRepository="Si"
        ;;
      "--delres" )
        shift
        deleteResources="Si"
        ;;
      "-m"|"--makesql" )
        shift
        generateSQLs
        ;;
      "-?"|"-h"|"--help" )
        help
        exit
        ;;
      * )
        help
        exit
    esac
done

