@ECHO OFF
SETLOCAL

REM   This will export data from PostgreSQL for use by DBDOC. This is likely to
REM   be faster than a full S+E backup, but it is more complex to set up. Please
REM   contact GMCL for assistance with this.

REM   Despite the name, this utility now dumps all tables and views, as this is
REM   not much slower than dumping the specific tables DBDOC uses and it makes
REM   this utility less likely to need updating for future versions of SPE.

REM   If this batch file is called with command line arguments, the first
REM   argument will override the default database username of "postgres", and
REM   the second will override the default database name taken from the batch
REM   file's path.

REM   The db user password, if needed, should be placed in the pgpass file
REM   https://www.postgresql.org/docs/current/libpq-pgpass.html


REM   Find the highest version of PostgreSQL installed so we can use its pg_dump
SET PGPATH=C:\Program Files\PostgreSQL\
IF NOT EXIST "%PGPATH%" SET PGPATH=C:\Program Files (x86)\PostgreSQL\
FOR /D %%a IN ("%PGPATH%??") DO (
  IF %%a GTR "%PGPATH%" (
    SET PGPATH=%%a
  )
)
SET PGDUMP="%PGPATH%\bin\pg_dump.exe"

SET DBUSER=postgres
IF NOT "%~1"=="" SET DBUSER=%1

REM   We expect this file to be in the folder [projects location]\Project\CH\DBDOC.
REM   We expect that generally Project is the name of the database.
FOR %%A IN ("%~dp0\.\..\..") DO SET "DBNAME=%%~nxA"
IF NOT "%~2"=="" SET DBNAME=%~2

SET OUTPUTFILE="%~dp0%dbdoc.sql"

%PGDUMP% -d "%DBNAME%" -U %DBUSER% -f %OUTPUTFILE% -E UTF8 -x --quote-all-identifiers --inserts --blobs --no-comments --no-owner --no-tablespaces --section=pre-data --section=data

ENDLOCAL