@echo off
echo The Inobitec DICOM Server ^(PACS^) uninstallation script

rem Confirm uninstall
choice /m "Do you really want to uninstall Inobitec DICOM Server (PACS)? This action can not be aborted."
if ERRORLEVEL 2 (goto end)

rem Stop server
set SERVICE_NAME=
set /p SERVICE_NAME="Enter the Inobitec DICOM Server (PACS) service name [PACSServer]: "
if "%SERVICE_NAME%"=="" set "SERVICE_NAME=PACSServer"
sc stop %SERVICE_NAME%

rem Delete database schema
choice /m "Do you want to delete database schema?"
if ERRORLEVEL 2 (goto delete_files)

set POSTGRES_APP=psql
where %POSTGRES_APP%>nul
if %ERRORLEVEL% equ 0 goto enter_params

set POSTGRES_APP_PATH=
set /p POSTGRES_APP_PATH="PostgreSQL client application is not found. Enter the path to application: "
if "%POSTGRES_APP_PATH%"=="" goto delete_files

set POSTGRES_APP=%POSTGRES_APP_PATH%

:enter_params
set DB_HOST=
set /p DB_HOST="Enter database host ip [127.0.0.1]: "
if "%DB_HOST%"=="" set "DB_HOST=127.0.0.1"
set DB_PORT=
set /p DB_PORT="Enter database port [5432]: "
if "%DB_PORT%"=="" set "DB_PORT=5432"
set DB_USER=
set /p DB_USER="Enter PostgreSQL administrator user name [postgres]: "
if "%DB_USER%"=="" set "DB_USER=postgres"
set DB_PASS=
set /p DB_PASS="Enter PostgreSQL administrator user password: "
set PGPASSWORD=%DB_PASS%
echo DROP DATABASE pacs; | "%POSTGRES_APP%" -U %DB_USER% -h %DB_HOST% -p %DB_PORT%
if ERRORLEVEL 1 goto drop_db_failed
goto delete_db_user

:drop_db_failed
echo Delete schema failed. You should to delete schema manually.
goto delete_files

:delete_db_user
choice /m "Do you want to delete database schema user?"
if ERRORLEVEL 2 (goto delete_files)
set PACS_USER=
set /p PACS_USER="Enter postgres user name for Inobitec DICOM Server (PACS) db scheme [PACS_USER]: "
if "%PACS_USER%"=="" set "PACS_USER=PACS_USER"
echo DROP USER "%PACS_USER%"; | "%POSTGRES_APP%" -U %DB_USER% -h %DB_HOST% -p %DB_PORT%
if ERRORLEVEL 1 goto delete_db_user_failed
goto delete_files

:delete_db_user_failed
echo Delete schema user failed. You should to delete schema user manually.

rem Delete all PACS files
:delete_files
choice /m "Do you want to delete Inobitec DICOM Server (PACS) files?"
if ERRORLEVEL 2 (goto end)

set DEST_DIR=
set /p DEST_DIR="Enter the path to the folder where Inobitec DICOM Server (PACS) is installed [C:\PACSServer]: "
if "%DEST_DIR%"=="" set "DEST_DIR=C:\PACSServer"
if not exist "%DEST_DIR%" (
  echo The directory %DEST_DIR% is not exists.
  goto failed
)

del /f /s /q %DEST_DIR%
if ERRORLEVEL 1 goto failed
rmdir /q /s %DEST_DIR%
if ERRORLEVEL 1 goto failed

sc delete %SERVICE_NAME%
if ERRORLEVEL 1 goto failed

echo Uninstalling Inobitec DICOM Server ^(PACS^) completed.
goto end

:failed
echo Uninstalling Inobitec DICOM Server ^(PACS^) failed.

:end
pause
