name: Build

permissions:
  contents: write

on:
  push:
  pull_request:

jobs:

  test:
    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v2

      - uses: actions/setup-java@v1
        with:
          java-version: 11

      - run: |
          chmod +x ./gradlew
          ./gradlew :ktlintCheck
          ./gradlew :app:testBlueDebugUnitTest


  build:
    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v2

      - uses: actions/setup-java@v1
        with:
          java-version: 11

      - run: |
          chmod +x ./gradlew
          ./gradlew :app:assembleBlueRelease

      - uses: r0adkll/sign-android-release@v1
        with:
          releaseDirectory: app/build/outputs/apk/blue/release
          signingKeyBase64: ${{ secrets.SIGNING_KEY }}
          alias: ${{ secrets.ALIAS }}
          keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }}
          keyPassword: ${{ secrets.KEY_PASSWORD }}

      - uses: actions/upload-artifact@v2
        with:
          name: built-app
          path: ${{ env.SIGNED_RELEASE_FILE }}


  draft:
    runs-on: ubuntu-latest
    needs: [test, build]
    if: github.event_name == 'push' && github.ref == 'refs/heads/master'

    steps:

      - uses: actions/checkout@v2

      - env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          curl -H "Authorization: Bearer $GITHUB_TOKEN" https://api.github.com/repos/$GITHUB_REPOSITORY/releases \
            | tr '\r\n' ' ' \
            | jq '.[] | select(.draft == true) | .id' \
            | xargs -I '{}' \
          curl -X DELETE -H "Authorization: Bearer $GITHUB_TOKEN" https://api.github.com/repos/$GITHUB_REPOSITORY/releases/{}

      - run: |
          DIR_TIMESTAMP=$(git log -1 --pretty="format:%ct" ./changelogs/)
          for d in ./changelogs/*/; do
            if [ $(git log -1 --pretty="format:%ct" "$d") = $DIR_TIMESTAMP ]; then
              echo "CHANGELOG_DIR=$d" >> $GITHUB_ENV
              echo "CHANGELOG_VERSION=$(basename -as / "$d")" >> $GITHUB_ENV
            fi
          done

      - uses: actions/download-artifact@v1
        with:
          name: built-app

      - run: |
          cd ./built-app
          mv "$(find . -type f -name "*.apk" | head -1)" "Yuito-${{ env.CHANGELOG_VERSION }}.apk"

      - uses: ncipollo/release-action@v1
        with:
          allowUpdates: false
          artifactErrorsFailBuild: true
          artifacts: ./built-app/Yuito-${{ env.CHANGELOG_VERSION }}.apk
          bodyFile: ${{ env.CHANGELOG_DIR }}whatsnew-en-US
          draft: true
          name: Yuito ${{ env.CHANGELOG_VERSION }}
          tag: ${{ env.CHANGELOG_VERSION }}
