name: Build Windows Installer

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      version:
        description: 'Version'
        required: false
      isDebug:
        description: 'Build debug version with console output'
        type: boolean 


env:
  JAVA_VERSION: 20
  JAVA_DIST: 'temurin'
  JAVA_CACHE: 'maven'
  JFX_JMODS_URL: 'https://download2.gluonhq.com/openjfx/20.0.1/openjfx-20.0.1_windows-x64_bin-jmods.zip'
  JFX_JMODS_HASH: 'D00767334C43B8832B5CF10267D34CA8F563D187C4655B73EB6020DD79C054B5'

defaults:
  run:
    shell: bash

jobs:
  get-version:
    uses: ./.github/workflows/get-version.yml
    with:
      version: ${{ inputs.version }}

  build-msi:
    name: Build .msi Installer
    runs-on: windows-latest
    needs: [get-version]
    env:
      LOOPBACK_ALIAS: 'cryptomator-vault'
      WIN_CONSOLE_FLAG: ''
    steps:
      - uses: actions/checkout@v3
      - name: Setup Java
        uses: actions/setup-java@v3
        with:
          distribution: ${{ env.JAVA_DIST }}
          java-version: ${{ env.JAVA_VERSION }}
          java-package: 'jdk'
          cache: ${{ env.JAVA_CACHE }}
      - name: Download and extract JavaFX jmods from Gluon
        #In the last step we move all jmods files a dir level up because jmods are placed inside a directory in the zip
        run: |
          curl --output jfxjmods.zip -L "${{ env.JFX_JMODS_URL }}"
          if(!(Get-FileHash -Path jfxjmods.zip -Algorithm SHA256).Hash.equals("${{ env.JFX_JMODS_HASH }}")) {
            throw "Wrong checksum of JMOD archive downloaded from ${{ env.JFX_JMODS_URL }}.";
          }
          Expand-Archive -Path jfxjmods.zip -DestinationPath jfxjmods
          Get-ChildItem -Path jfxjmods -Recurse -Filter "*.jmod" | ForEach-Object { Move-Item -Path $_ -Destination $_.Directory.Parent}
        shell: pwsh
      - name: Ensure major jfx version in pom and in jmods is the same
        run: |
          JMOD_VERSION_AMD64=$(jmod describe jfxjmods/javafx.base.jmod | head -1)
          JMOD_VERSION_AMD64=${JMOD_VERSION_AMD64#*@}
          JMOD_VERSION_AMD64=${JMOD_VERSION_AMD64%%.*}
          POM_JFX_VERSION=$(mvn help:evaluate "-Dexpression=javafx.version" -q -DforceStdout)
          POM_JFX_VERSION=${POM_JFX_VERSION#*@}
          POM_JFX_VERSION=${POM_JFX_VERSION%%.*}

          if [ $POM_JFX_VERSION -ne $JMOD_VERSION_AMD64 ]; then
            >&2 echo "Major JavaFX version in pom.xml (${POM_JFX_VERSION}) != amd64 jmod version (${JMOD_VERSION_AMD64})"
            exit 1
          fi
      - name: Set version
        run : mvn versions:set -DnewVersion=${{ needs.get-version.outputs.semVerStr }}
      - name: Run maven
        run: mvn -B clean package -Pdependency-check,win -DskipTests
      - name: Patch target dir
        run: |
          cp LICENSE.txt target
          cp target/cryptomator-*.jar target/mods
      - name: Run jlink
        run: >
          ${JAVA_HOME}/bin/jlink
          --verbose
          --output runtime
          --module-path "jfxjmods;${JAVA_HOME}/jmods"
          --add-modules java.base,java.desktop,java.instrument,java.logging,java.naming,java.net.http,java.scripting,java.sql,java.xml,javafx.base,javafx.graphics,javafx.controls,javafx.fxml,jdk.unsupported,jdk.crypto.ec,jdk.accessibility,jdk.management.jfr
          --strip-native-commands
          --no-header-files
          --no-man-pages
          --strip-debug
          --compress=1
      - name: Change win-console flag if debug is active
        if: ${{ inputs.isDebug }}
        run: echo "WIN_CONSOLE_FLAG=--win-console" >> $GITHUB_ENV
      - name: Run jpackage
        run: >
          ${JAVA_HOME}/bin/jpackage
          --verbose
          --type app-image
          --runtime-image runtime
          --input target/libs
          --module-path target/mods
          --module org.cryptomator.desktop/org.cryptomator.launcher.Cryptomator
          --dest appdir
          --name Cryptomator
          --vendor "Skymatic GmbH"
          --copyright "(C) 2016 - 2023 Skymatic GmbH"
          --app-version "${{ needs.get-version.outputs.semVerNum }}.${{ needs.get-version.outputs.revNum }}"
          --java-options "--enable-preview"
          --java-options "--enable-native-access=org.cryptomator.jfuse.win"
          --java-options "-Xss5m"
          --java-options "-Xmx256m"
          --java-options "-Dcryptomator.appVersion=\"${{ needs.get-version.outputs.semVerStr }}\""
          --java-options "-Dfile.encoding=\"utf-8\""
          --java-options "-Djava.net.useSystemProxies=true"
          --java-options "-Dcryptomator.logDir=\"@{localappdata}/Cryptomator\""
          --java-options "-Dcryptomator.pluginDir=\"@{appdata}/Cryptomator/Plugins\""
          --java-options "-Dcryptomator.settingsPath=\"@{appdata}/Cryptomator/settings.json;@{userhome}/AppData/Roaming/Cryptomator/settings.json\""
          --java-options "-Dcryptomator.p12Path=\"@{appdata}/Cryptomator/key.p12;@{userhome}/AppData/Roaming/Cryptomator/key.p12\""
          --java-options "-Dcryptomator.ipcSocketPath=\"@{localappdata}/Cryptomator/ipc.socket\""
          --java-options "-Dcryptomator.mountPointsDir=\"@{userhome}/Cryptomator\""
          --java-options "-Dcryptomator.loopbackAlias=\"${{ env.LOOPBACK_ALIAS }}\""
          --java-options "-Dcryptomator.showTrayIcon=true"
          --java-options "-Dcryptomator.buildNumber=\"msi-${{ needs.get-version.outputs.revNum }}\""
          --java-options "-Dcryptomator.integrationsWin.autoStartShellLinkName=\"Cryptomator\""
          --java-options "-Dcryptomator.integrationsWin.keychainPaths=\"@{appdata}/Cryptomator/keychain.json;@{userhome}/AppData/Roaming/Cryptomator/keychain.json\""
          --java-options "-Djavafx.verbose=${{ inputs.isDebug }}"
          --resource-dir dist/win/resources
          --icon dist/win/resources/Cryptomator.ico
          ${WIN_CONSOLE_FLAG}
      - name: Patch Application Directory
        run: |
          cp dist/win/contrib/* appdir/Cryptomator
      - name: Set LOOPBACK_ALIAS in patchWebDAV.bat
        shell: pwsh
        run: |
          $patchScript = "appdir\Cryptomator\patchWebDAV.bat"
          try {
            (Get-Content $patchScript ) -replace '::REPLACE ME', "SET LOOPBACK_ALIAS=`"${{ env.LOOPBACK_ALIAS}}`"" | Set-Content $patchScript
          } catch {
            Write-Host "Failed to set LOOPBACK_ALIAS for patchWebDAV.bat"
            exit 1
          }
      - name: Fix permissions
        run: attrib -r appdir/Cryptomator/Cryptomator.exe
        shell: pwsh
      - name: Extract integrations DLL for code signing
        shell: pwsh
        run: gci ./appdir/Cryptomator/app/mods/ -File integrations-win-*.jar | ForEach-Object {Set-Location -Path $_.Directory; jar --file=$($_.FullName) --extract integrations.dll }
      - name: Codesign
        uses: skymatic/code-sign-action@v2
        with:
          certificate: ${{ secrets.WIN_CODESIGN_P12_BASE64 }}
          password: ${{ secrets.WIN_CODESIGN_P12_PW }}
          certificatesha1: 5FC94CE149E5B511E621F53A060AC67CBD446B3A
          description: Cryptomator
          timestampUrl: 'http://timestamp.digicert.com'
          folder: appdir/Cryptomator
          recursive: true
      - name: Repack signed DLL into jar
        shell: pwsh
        run: |
          gci ./appdir/Cryptomator/app/mods/ -File integrations-win-*.jar | ForEach-Object {Set-Location -Path $_.Directory; jar --file=$($_.FullName) --update integrations.dll; Remove-Item integrations.dll}
      - name: Generate license for MSI
        run: >
          mvn -B license:add-third-party
          "-Dlicense.thirdPartyFilename=license.rtf"
          "-Dlicense.outputDirectory=dist/win/resources"
          "-Dlicense.fileTemplate=dist/win/resources/licenseTemplate.ftl"
          "-Dlicense.includedScopes=compile"
          "-Dlicense.excludedGroups=^org\.cryptomator"
          "-Dlicense.failOnMissing=true"
          "-Dlicense.licenseMergesUrl=file:///${{ github.workspace }}/license/merges"
        shell: pwsh
      - name: Create MSI
        run: >
          ${JAVA_HOME}/bin/jpackage
          --verbose
          --type msi
          --win-upgrade-uuid bda45523-42b1-4cae-9354-a45475ed4775
          --app-image appdir/Cryptomator
          --dest installer
          --name Cryptomator
          --vendor "Skymatic GmbH"
          --copyright "(C) 2016 - 2023 Skymatic GmbH"
          --app-version "${{ needs.get-version.outputs.semVerNum }}.${{ needs.get-version.outputs.revNum}}"
          --win-menu
          --win-dir-chooser
          --win-shortcut-prompt
          --win-update-url "https:\\cryptomator.org"
          --win-menu-group Cryptomator
          --resource-dir dist/win/resources
          --license-file dist/win/resources/license.rtf
          --file-associations dist/win/resources/FAvaultFile.properties
        env:
          JP_WIXWIZARD_RESOURCES: ${{ github.workspace }}/dist/win/resources # requires abs path, used in resources/main.wxs
      - name: Codesign MSI
        uses: skymatic/code-sign-action@v2
        with:
          certificate: ${{ secrets.WIN_CODESIGN_P12_BASE64 }}
          password: ${{ secrets.WIN_CODESIGN_P12_PW }}
          certificatesha1: 5FC94CE149E5B511E621F53A060AC67CBD446B3A
          description: Cryptomator Installer
          timestampUrl: 'http://timestamp.digicert.com'
          folder: installer
      - name: Add possible alpha/beta tags to installer name
        run: mv installer/Cryptomator-*.msi Cryptomator-${{ needs.get-version.outputs.semVerStr }}-x64.msi
      - name: Create detached GPG signature with key 615D449FE6E6A235
        run: |
          echo "${GPG_PRIVATE_KEY}" | gpg --batch --quiet --import
          echo "${GPG_PASSPHRASE}" | gpg --batch --quiet --passphrase-fd 0 --pinentry-mode loopback -u 615D449FE6E6A235 --detach-sign -a Cryptomator-*.msi
        env:
          GPG_PRIVATE_KEY: ${{ secrets.RELEASES_GPG_PRIVATE_KEY }}
          GPG_PASSPHRASE: ${{ secrets.RELEASES_GPG_PASSPHRASE }}
      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          name: msi
          path: |
            Cryptomator-*.msi
            Cryptomator-*.asc
          if-no-files-found: error
      - name: Publish .msi on GitHub Releases
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v1
        with:
          fail_on_unmatched_files: true
          token: ${{ secrets.CRYPTOBOT_RELEASE_TOKEN }}
          files: |
            *.msi
            *.asc

  build-exe:
    name: Build .exe installer
    runs-on: windows-latest
    needs: [get-version, build-msi]
    steps:
      - uses: actions/checkout@v3
      - name: Download .msi
        uses: actions/download-artifact@v3
        with:
          name: msi
          path: dist/win/bundle/resources
      - name: Strip version info from msi file name
        run: mv dist/win/bundle/resources/Cryptomator*.msi dist/win/bundle/resources/Cryptomator.msi
      - uses: actions/setup-java@v3
        with:
          distribution: ${{ env.JAVA_DIST }}
          java-version: ${{ env.JAVA_VERSION }}
          cache: ${{ env.JAVA_CACHE }}
      - name: Generate license for exe
        run: >
          mvn -B license:add-third-party
          "-Dlicense.thirdPartyFilename=license.rtf"
          "-Dlicense.fileTemplate=dist/win/bundle/resources/licenseTemplate.ftl"
          "-Dlicense.outputDirectory=dist/win/bundle/resources"
          "-Dlicense.includedScopes=compile"
          "-Dlicense.excludedGroups=^org\.cryptomator"
          "-Dlicense.failOnMissing=true"
          "-Dlicense.licenseMergesUrl=file:///${{ github.workspace }}/license/merges"
        shell: pwsh
      - name: Download WinFsp
        run: |
          $winfspUrl = (Select-String -Path ".\dist\win\bundle\resources\winFspMetaData.wxi" -Pattern '<\?define BundledWinFspDownloadLink="(.+)".*?>').Matches.Groups[1].Value
          curl --output dist/win/bundle/resources/winfsp.msi -L $winfspUrl
        shell: pwsh
      - name: Compile to wixObj file
        run: >
          "${WIX}/bin/candle.exe" dist/win/bundle/bundleWithWinfsp.wxs
          -ext WixBalExtension
          -ext WixUtilExtension
          -out dist/win/bundle/
          -dBundleVersion="${{ needs.get-version.outputs.semVerNum }}.${{ needs.get-version.outputs.revNum }}"
          -dBundleVendor="Skymatic GmbH"
          -dBundleCopyright="(C) 2016 - 2023 Skymatic GmbH"
          -dAboutUrl="https://cryptomator.org"
          -dHelpUrl="https://cryptomator.org/contact"
          -dUpdateUrl="https://cryptomator.org/downloads/"
      - name: Create executable with linker
        run: >
          "${WIX}/bin/light.exe" -b dist/win/ dist/win/bundle/bundleWithWinfsp.wixobj
          -ext WixBalExtension
          -ext WixUtilExtension
          -out installer/unsigned/Cryptomator-Installer.exe
      - name: Detach burn engine in preparation to sign
        run: >
          "${WIX}/bin/insignia.exe"
          -ib installer/unsigned/Cryptomator-Installer.exe
          -o tmp/engine.exe
      - name: Codesign burn engine
        uses: skymatic/code-sign-action@v2
        with:
          certificate: ${{ secrets.WIN_CODESIGN_P12_BASE64 }}
          password: ${{ secrets.WIN_CODESIGN_P12_PW }}
          certificatesha1: 5FC94CE149E5B511E621F53A060AC67CBD446B3A
          description: Cryptomator Installer
          timestampUrl: 'http://timestamp.digicert.com'
          folder: tmp
      - name: Reattach signed burn engine to installer
        run : >
          "${WIX}/bin/insignia.exe"
          -ab tmp/engine.exe installer/unsigned/Cryptomator-Installer.exe
          -o installer/Cryptomator-Installer.exe
      - name: Codesign EXE
        uses: skymatic/code-sign-action@v2
        with:
          certificate: ${{ secrets.WIN_CODESIGN_P12_BASE64 }}
          password: ${{ secrets.WIN_CODESIGN_P12_PW }}
          certificatesha1: 5FC94CE149E5B511E621F53A060AC67CBD446B3A
          description: Cryptomator Installer
          timestampUrl: 'http://timestamp.digicert.com'
          folder: installer
      - name: Add possible alpha/beta tags to installer name
        run: mv installer/Cryptomator-Installer.exe Cryptomator-${{ needs.get-version.outputs.semVerStr }}-x64.exe
      - name: Create detached GPG signature with key 615D449FE6E6A235
        run: |
          echo "${GPG_PRIVATE_KEY}" | gpg --batch --quiet --import
          echo "${GPG_PASSPHRASE}" | gpg --batch --quiet --passphrase-fd 0 --pinentry-mode loopback -u 615D449FE6E6A235 --detach-sign -a Cryptomator-*.exe
        env:
          GPG_PRIVATE_KEY: ${{ secrets.RELEASES_GPG_PRIVATE_KEY }}
          GPG_PASSPHRASE: ${{ secrets.RELEASES_GPG_PASSPHRASE }}
      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          name: exe
          path: |
            Cryptomator-*.exe
            Cryptomator-*.asc
          if-no-files-found: error
      - name: Publish .msi on GitHub Releases
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v1
        with:
          fail_on_unmatched_files: true
          token: ${{ secrets.CRYPTOBOT_RELEASE_TOKEN }}
          files: |
            Cryptomator-*.exe
            Cryptomator-*.asc

  allowlist:
    name: Anti Virus Allowlisting
    if: startsWith(github.ref, 'refs/tags/')
    runs-on: ubuntu-latest
    needs: [build-msi, build-exe]
    steps:
      - name: Download .msi
        uses: actions/download-artifact@v3
        with:
          name: msi
          path: msi
      - name: Download .exe
        uses: actions/download-artifact@v3
        with:
          name: exe
          path: exe
      - name: Collect files
        run: |
          mkdir files
          cp msi/*.msi files
          cp exe/*.exe files
      - name: Upload to Kaspersky
        uses: SamKirkland/FTP-Deploy-Action@4.3.3
        with:
          protocol: ftps
          server: allowlist.kaspersky-labs.com
          port: 990
          username: ${{ secrets.ALLOWLIST_KASPERSKY_USERNAME }}
          password: ${{ secrets.ALLOWLIST_KASPERSKY_PASSWORD }}
          local-dir: files/
      - name: Upload to Avast
        uses: SamKirkland/FTP-Deploy-Action@4.3.0
        with:
          protocol: ftp
          server: whitelisting.avast.com
          port: 21
          username: ${{ secrets.ALLOWLIST_AVAST_USERNAME }}
          password: ${{ secrets.ALLOWLIST_AVAST_PASSWORD }}
          local-dir: files/