name: CI

on: [push, pull_request]

env:
  IMAGE: ${{ github.repository }}
  TAG: ${{ github.sha }}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2

    - uses: actions/setup-node@v1
      with:
        node-version: '12.x'

    - name: Install dependencies
      run: yarn install

    - name: Build
      run: |
        export VUE_APP_BUILD=$TAG
        export VUE_APP_BUILD_DATE=$(date --iso-8601)
        yarn build

    - name: Upload artifact
      uses: actions/upload-artifact@v2
      with:
        name: dist
        path: dist

    - name: Build docker image
      run: docker build -t $IMAGE:$TAG -f docker/Dockerfile .

    - name: Push docker image
      run: |
        docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} -p ${{ secrets.DOCKER_HUB_PASSWORD }}
        docker push $IMAGE:$TAG

  preview:
    runs-on: ubuntu-latest
    needs: build
    if: github.ref != 'refs/heads/master'
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v2
        with:
          name: dist

      - name: Deploy preview
        uses: netlify/actions/cli@master
        env:
          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
        with:
          args: deploy --dir=.

  deploy:
    runs-on: ubuntu-latest
    needs: build
    if: github.ref == 'refs/heads/master'
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v2
        with:
          name: dist

      - name: Deploy site
        uses: netlify/actions/cli@master
        env:
          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
        with:
          args: deploy --dir=. --prod

  publish_docker_image:
    runs-on: ubuntu-latest
    needs: build
    if: github.ref == 'refs/heads/master'
    steps:
      - name: Push latest
        run: |
          docker pull $IMAGE:$TAG
          docker tag $IMAGE:$TAG $IMAGE:latest
          docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} -p ${{ secrets.DOCKER_HUB_PASSWORD }}
          docker push $IMAGE:latest
