name: Deploy triz-docs to civital server

on:
  push:
    branches: [ main ]

jobs:
  build-and-deploy:
    runs-on: serveurtest150

    env:
      GIT_REPO_URL: 145.239.66.197:3000/TrizTech/triz-docs.git
      BRANCH: main
      WORKSPACE_DIR: C:\CICD\workspace\triz-docs
      DEPLOY_DIR: C:\inetpub\wwwroot\docs
      NODE_PATH: C:\Program Files\nodejs

    steps:

      # --------------------------------------------------
      # 1. Clean slate
      # --------------------------------------------------
      - name: Prepare workspace
        shell: cmd
        run: |
          if exist "%WORKSPACE_DIR%" rmdir /S /Q "%WORKSPACE_DIR%"
          mkdir "%WORKSPACE_DIR%"
          if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL%

      # --------------------------------------------------
      # 2. Clone source code
      # --------------------------------------------------
      - name: Clone source code
        shell: cmd
        env:
          GIT_TOKEN: ${{ secrets.GITEAACTTOKEN }}
        run: |
          git -c credential.helper= clone --depth 1 --branch %BRANCH% http://ciRunner:%GIT_TOKEN%@%GIT_REPO_URL% "%WORKSPACE_DIR%"
          if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL%

      # --------------------------------------------------
      # 3. Install dependencies
      # --------------------------------------------------
      - name: Install dependencies
        shell: cmd
        run: |
          set PATH=%NODE_PATH%;%PATH%
          cd /d "%WORKSPACE_DIR%"

          echo [diag] Running npm install...
          npm install

          if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL%

      # --------------------------------------------------
      # 4. Build
      # --------------------------------------------------
      - name: Build
        shell: cmd
        run: |
          set PATH=%NODE_PATH%;%PATH%
          cd /d "%WORKSPACE_DIR%"

          if not exist "node_modules" (
            echo node_modules missing
            exit /b 1
          )

          npm run build

          if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL%

      # --------------------------------------------------
      # 5. Deploy
      # --------------------------------------------------
      - name: Deploy
        shell: cmd
        run: |
          if not exist "%DEPLOY_DIR%" mkdir "%DEPLOY_DIR%"

          robocopy "%WORKSPACE_DIR%\build" "%DEPLOY_DIR%" /E /PURGE /NFL /NDL /NJH /NJS
          set RC=%ERRORLEVEL%

          echo Robocopy exit code: %RC%

          if %RC% GEQ 8 exit /b %RC%

      # --------------------------------------------------
      # 6. Cleanup
      # --------------------------------------------------
      - name: Cleanup workspace
        if: always()
        shell: cmd
        run: |
          if exist "%WORKSPACE_DIR%" rmdir /S /Q "%WORKSPACE_DIR%"