name: Android CI for releases

on:
  push:
    # Pattern matched against refs/tags
    tags:
      - '*'           # Push events to every tag

jobs:
  release:

    runs-on: ubuntu-latest

    steps:
      - name: Checkout Git repository
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Fetch Git tags
        run: git fetch --tags
      - name: set up JDK 1.8
        uses: actions/setup-java@v1
        with:
          java-version: 1.8
      - name: Cache local Gradle repository
        uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
          restore-keys: |
            ${{ runner.os }}-gradle-
      - name: Grant execute permission for gradlew
        run: chmod +x gradlew
      - name: Build with Gradle
        run: ./gradlew build -Pbuild=prod
      - name: Sign artifact
        id: signArtifact
        uses: r0adkll/sign-android-release@v1
        with:
          releaseDirectory: app/build/outputs/apk/release/release
          alias: ${{ secrets.ALIAS }}
          signingKeyBase64: ${{ secrets.KEYSTORE }}
          keyStorePassword: ${{ secrets.KEYSTORE_PASSWORD }}
          keyPassword: ${{ secrets.KEY_PASSWORD }}
      - name: Upload artifact
        uses: actions/upload-artifact@v2
        with:
          name: Release artifact
          path: app/build/outputs/apk/release/release/SWADroid-*.apk
      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ github.ref }}
          release_name: Release ${{ github.ref }}
          draft: false
          prerelease: false
      - name: Save name of Artifact
        id: set-result-artifact
        run: |
          ARTIFACT_PATHNAME_APK=$(ls app/build/outputs/apk/release/release/*.apk | head -n 1)
          ARTIFACT_NAME_APK=$(basename $ARTIFACT_PATHNAME_APK)
          echo "ARTIFACT_NAME_APK is " ${ARTIFACT_NAME_APK}
          echo "ARTIFACT_PATHNAME_APK=${ARTIFACT_PATHNAME_APK}" >> $GITHUB_ENV
          echo "ARTIFACT_NAME_APK=${ARTIFACT_NAME_APK}" >> $GITHUB_ENV
      - name: Upload Artifact Assets
        id: upload-release-asset
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          upload_url: ${{ steps.create_release.outputs.upload_url }}
          asset_path: ${{ env.ARTIFACT_PATHNAME_APK }}
          asset_name: ${{ env.ARTIFACT_NAME_APK }}
          asset_content_type: application/zip
