@echo off
setlocal

set APP_NAME=MailsAuswerten
set INSTALL_DIR=%LOCALAPPDATA%\%APP_NAME%\App
set DATA_DIR=%LOCALAPPDATA%\%APP_NAME%\Data
set SHORTCUT_NAME=%APP_NAME%.lnk
set EXE_NAME=MailsAuswerten.exe

echo.
echo ============================================
echo   %APP_NAME% - Installation
echo ============================================
echo.
echo Installationsverzeichnis: %INSTALL_DIR%
echo Datenverzeichnis:         %DATA_DIR%
echo.

:: Zielverzeichnisse erstellen
if not exist "%INSTALL_DIR%" mkdir "%INSTALL_DIR%"
if not exist "%DATA_DIR%" mkdir "%DATA_DIR%"
if not exist "%DATA_DIR%\attachments" mkdir "%DATA_DIR%\attachments"
if not exist "%DATA_DIR%\backups" mkdir "%DATA_DIR%\backups"

:: App-Dateien kopieren (aus dem Ordner in dem install.bat liegt)
echo [1/4] Kopiere Anwendungsdateien...
set SOURCE_DIR=%~dp0app
if not exist "%SOURCE_DIR%" (
    echo FEHLER: Ordner "app" nicht gefunden neben install.bat!
    echo Erwartet: %SOURCE_DIR%
    pause
    exit /b 1
)
xcopy /E /Y /Q "%SOURCE_DIR%\*" "%INSTALL_DIR%\" >nul
if errorlevel 1 (
    echo FEHLER beim Kopieren!
    pause
    exit /b 1
)

:: Standard-Konfiguration erstellen (falls nicht vorhanden)
echo [2/4] Konfiguration vorbereiten...
if not exist "%DATA_DIR%\config.ini" (
    echo [STORAGE]> "%DATA_DIR%\config.ini"
    echo attachment_dir = attachments>> "%DATA_DIR%\config.ini"
    echo database_path = mails.db>> "%DATA_DIR%\config.ini"
)
if not exist "%DATA_DIR%\accounts.json" (
    echo []> "%DATA_DIR%\accounts.json"
)

:: Desktop-Verknuepfung erstellen
echo [3/4] Desktop-Verknuepfung erstellen...
powershell -NoProfile -Command "$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut('%USERPROFILE%\Desktop\%SHORTCUT_NAME%'); $s.TargetPath = '%INSTALL_DIR%\%EXE_NAME%'; $s.WorkingDirectory = '%INSTALL_DIR%'; $s.IconLocation = '%INSTALL_DIR%\icon.ico'; $s.Description = 'E-Mail Auswertungs-Tool'; $s.Save()"

:: Startmenue-Verknuepfung erstellen
echo [4/4] Startmenue-Eintrag erstellen...
set START_MENU=%APPDATA%\Microsoft\Windows\Start Menu\Programs
powershell -NoProfile -Command "$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut('%START_MENU%\%SHORTCUT_NAME%'); $s.TargetPath = '%INSTALL_DIR%\%EXE_NAME%'; $s.WorkingDirectory = '%INSTALL_DIR%'; $s.IconLocation = '%INSTALL_DIR%\icon.ico'; $s.Description = 'E-Mail Auswertungs-Tool'; $s.Save()"

:: Deinstaller kopieren
copy /Y "%~dp0uninstall.bat" "%INSTALL_DIR%\uninstall.bat" >nul

echo.
echo ============================================
echo   Installation abgeschlossen!
echo ============================================
echo.
echo Starten: Desktop-Symbol "%APP_NAME%" oder Startmenue
echo.
echo Moechten Sie %APP_NAME% jetzt starten? (J/N)
set /p START_NOW=
if /i "%START_NOW%"=="J" (
    start "" "%INSTALL_DIR%\%EXE_NAME%"
)
