name: release.yml
on:
  pull_request:
    types: [closed]
    paths:
      - CHANGELOG.md

jobs:
  # Maybe double check PR source branch?

  merge_translations:
    uses: ./.github/workflows/merge-translations.yml
    permissions:
      pull-requests: write
    secrets:
      PUSH_O_MATIC_APP_ID: ${{ secrets.PUSH_O_MATIC_APP_ID }}
      PUSH_O_MATIC_APP_KEY: ${{ secrets.PUSH_O_MATIC_APP_KEY }}
      WEBLATE_TOKEN: ${{ secrets.WEBLATE_TOKEN }}

  build_mobile:
    uses: ./.github/workflows/build-mobile.yml
    needs: merge_translations
    permissions:
      contents: read
    secrets:
      KEY_JKS: ${{ secrets.KEY_JKS }}
      ALIAS: ${{ secrets.ALIAS }}
      ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
      ANDROID_STORE_PASSWORD: ${{ secrets.ANDROID_STORE_PASSWORD }}
      # iOS secrets
      APP_STORE_CONNECT_API_KEY_ID: ${{ secrets.APP_STORE_CONNECT_API_KEY_ID }}
      APP_STORE_CONNECT_API_KEY_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_API_KEY_ISSUER_ID }}
      APP_STORE_CONNECT_API_KEY: ${{ secrets.APP_STORE_CONNECT_API_KEY }}
      IOS_CERTIFICATE_P12: ${{ secrets.IOS_CERTIFICATE_P12 }}
      IOS_CERTIFICATE_PASSWORD: ${{ secrets.IOS_CERTIFICATE_PASSWORD }}
      IOS_PROVISIONING_PROFILE: ${{ secrets.IOS_PROVISIONING_PROFILE }}
      IOS_PROVISIONING_PROFILE_SHARE_EXTENSION: ${{ secrets.IOS_PROVISIONING_PROFILE_SHARE_EXTENSION }}misc/release/notes.tmpl
      IOS_PROVISIONING_PROFILE_WIDGET_EXTENSION: ${{ secrets.IOS_PROVISIONING_PROFILE_WIDGET_EXTENSION }}
      IOS_DEVELOPMENT_PROVISIONING_PROFILE: ${{ secrets.IOS_DEVELOPMENT_PROVISIONING_PROFILE }}
      IOS_DEVELOPMENT_PROVISIONING_PROFILE_SHARE_EXTENSION: ${{ secrets.IOS_DEVELOPMENT_PROVISIONING_PROFILE_SHARE_EXTENSION }}
      IOS_DEVELOPMENT_PROVISIONING_PROFILE_WIDGET_EXTENSION: ${{ secrets.IOS_DEVELOPMENT_PROVISIONING_PROFILE_WIDGET_EXTENSION }}
      FASTLANE_TEAM_ID: ${{ secrets.FASTLANE_TEAM_ID }}
    with:
      ref: main
      environment: production

  prepare_release:
    runs-on: ubuntu-latest
    needs: build_mobile
    permissions:
      actions: read # To download the app artifact
    steps:
      - name: Generate a token
        id: generate-token
        uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1
        with:
          app-id: ${{ secrets.PUSH_O_MATIC_APP_ID }}
          private-key: ${{ secrets.PUSH_O_MATIC_APP_KEY }}

      - name: Checkout
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
        with:
          token: ${{ steps.generate-token.outputs.token }}
          persist-credentials: false
          ref: main

      - name: Extract changelog
        id: changelog
        run: |
          CHANGELOG_PATH=$RUNNER_TEMP/changelog.md
          sed -n '1,/^---$/p' CHANGELOG.md | head -n -1 > $CHANGELOG_PATH
          echo "path=$CHANGELOG_PATH" >> $GITHUB_OUTPUT
          VERSION=$(sed -n 's/^# //p' $CHANGELOG_PATH)
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Download APK
        uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
        with:
          name: release-apk-signed
          github-token: ${{ steps.generate-token.outputs.token }}

      - name: Create draft release
        uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2.5.0
        with:
          tag_name: ${{ steps.version.outputs.result }}
          token: ${{ steps.generate-token.outputs.token }}
          body_path: ${{ steps.changelog.outputs.path }}
          draft: true
          files: |
            docker/docker-compose.yml
            docker/example.env
            docker/hwaccel.ml.yml
            docker/hwaccel.transcoding.yml
            docker/prometheus.yml
            *.apk

      - name: Rename Outline document
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
        continue-on-error: true
        env:
          OUTLINE_API_KEY: ${{ secrets.OUTLINE_API_KEY }}
          VERSION: ${{ steps.changelog.outputs.version }}
        with:
          github-token: ${{ steps.generate-token.outputs.token }}
          script: |
            const outlineKey = process.env.OUTLINE_API_KEY;
            const version = process.env.VERSION;
            const parentDocumentId = 'da856355-0844-43df-bd71-f8edce5382d9';
            const baseUrl = 'https://outline.immich.cloud';

            const listResponse = await fetch(`${baseUrl}/api/documents.list`, {
              method: 'POST',
              headers: {
                'Authorization': `Bearer ${outlineKey}`,
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({ parentDocumentId })
            });

            if (!listResponse.ok) {
              throw new Error(`Outline list failed: ${listResponse.statusText}`);
            }

            const listData = await listResponse.json();
            const allDocuments = listData.data || [];
            const document = allDocuments.find(doc => doc.title === 'next');

            if (document) {
              console.log(`Found document 'next', renaming to '${version}'...`);

              const updateResponse = await fetch(`${baseUrl}/api/documents.update`, {
                method: 'POST',
                headers: {
                  'Authorization': `Bearer ${outlineKey}`,
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                  id: document.id,
                  title: version
                })
              });

              if (!updateResponse.ok) {
                throw new Error(`Failed to rename document: ${updateResponse.statusText}`);
              }
            } else {
              console.log('No document titled "next" found to rename');
            }
