version: 2
machine:
  environment:
    GRADLE_OPTS: '-Dorg.gradle.jvmargs="-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError"'
jobs:
  test:
    working_directory: ~/code
    docker:
      - image: circleci/android:api-27-alpha
    environment:
      JVM_OPTS: -Xmx3200m
    steps:
      - checkout
      - restore_cache:
          key: jars-{{ checksum "build.gradle" }}-{{ checksum  "app/build.gradle" }}
#      - run:
#         name: Chmod permissions #if permission for Gradlew Dependencies fail, use this. 
#         command: sudo chmod +x ./gradlew
      - run:
          name: Download Dependencies
          command: ./gradlew androidDependencies
      - save_cache:
          paths:
            - ~/.gradle
          key: jars-{{ checksum "build.gradle" }}-{{ checksum  "app/build.gradle" }}
      - run:
          name: Run Tests
          command: ./gradlew test
      - store_artifacts:
          path: app/build/reports
          destination: reports
      - store_test_results:
          path: app/build/test-results
  build:
    working_directory: ~/code
    docker:
      - image: circleci/android:api-27-alpha
    environment:
      JVM_OPTS: -Xmx3200m
    steps:
      - checkout
      - restore_cache:
          key: jars-{{ checksum "build.gradle" }}-{{ checksum  "app/build.gradle" }}
      - run:
          name: Build apk
          command: |
            ./gradlew assembleRelease --no-daemon --stacktrace
            /opt/android/sdk/build-tools/27.0.3/zipalign -v -p 4 app/build/outputs/apk/release/app-release-unsigned.apk app-release-aligned.apk
            keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -dname "C=US, O=Android, CN=Android Debug"
            /opt/android/sdk/build-tools/27.0.3/apksigner sign --ks debug.keystore --out app-release.apk --ks-pass pass:android app-release-aligned.apk
      - store_artifacts:
          path: app-release.apk
          destination: app-release.apk
workflows:
  version: 2
  test-and-build:
    jobs:
      - test
      - build:
          requires:
            - test
