name: CI

# Controls when the action will run. Triggers the workflow on push to master or development 
# with a tag like v1.0.0 or v1.0.0-dev
on:
  push:
    tags: 
      - v[0-9]+.[0-9]+.[0-9]+
      - v[0-9]+.[0-9]+.[0-9]+-[a-zA-Z]+

jobs:
  build:
    runs-on: ubuntu-latest

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v2
      
      - name: Get Version
        id: get_version
        uses: battila7/get-version-action@v2.0.0

      - name: Build container image
        env:
          IMAGE_TAG: ${{ steps.get_version.outputs.version-without-v }}
        run: docker build -t registry.digitalocean.com/djpianalto/goff:$IMAGE_TAG .

      - name: Install doctl
        uses: digitalocean/action-doctl@v2
        with:
          token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }}

      - name: Login to DigitalOcean Container Registry with short-lived credentials
        run: doctl registry login --expiry-seconds 600

      - name: Push image to DigitalOcean Container Registry
        env:
          IMAGE_TAG: ${{ steps.get_version.outputs.version-without-v }}
        run: docker push registry.digitalocean.com/djpianalto/goff:$IMAGE_TAG

      - name: Update deployment file
        run: TAG=${{ steps.get_version.outputs.version-without-v }} && sed -i 's|<IMAGE>|registry.digitalocean.com/djpianalto/goff:'${TAG}'|' $GITHUB_WORKSPACE/deployment.yml

      - name: Save DigitalOcean kubeconfig with short-lived credentials
        run: doctl kubernetes cluster kubeconfig save --expiry-seconds 600 discord-bots

      - name: Deploy to DigitalOcean Kubernetes
        run: kubectl apply -f $GITHUB_WORKSPACE/deployment.yml

      - name: Verify deployment
        run: kubectl rollout status deployment/goff
