@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 MYSQL_APP=mysql
where %MYSQL_APP%>nul
if %ERRORLEVEL% equ 0 goto enter_params

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

set MYSQL_APP=%MYSQL_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 [3306]: "
if "%DB_PORT%"=="" set "DB_PORT=3306"
set DB_USER=
set /p DB_USER="Enter mysql administrator user name [root]: "
if "%DB_USER%"=="" set "DB_USER=root"
set DB_PASS=
set /p DB_PASS="Enter mysql administrator user password: "
echo DROP DATABASE pacs; | "%MYSQL_APP%" -u %DB_USER% -p%DB_PASS% -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 mysql user name for Inobitec DICOM Server (PACS) db scheme [PACS_USER]: "
if "%PACS_USER%"=="" set "PACS_USER=PACS_USER"
echo DROP USER '%PACS_USER%'@'%%'; | "%MYSQL_APP%" -u %DB_USER% -p%DB_PASS% -h %DB_HOST% -P %DB_PORT%
if ERRORLEVEL 1 goto delete_db_user_failed
echo DROP USER '%PACS_USER%'@'localhost'; | "%MYSQL_APP%" -u %DB_USER% -p%DB_PASS% -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
