name: "Staging deployment"

on:
  release:
    types: ["published"]

jobs:
  build-for-staging:
    name: "Build"
    uses: "./.gitea/workflows/build-deployment-images.yaml"
    with:
      target: "aio"
      platform: "linux/amd64"
    secrets:
      VAULT_ROLE_ID: "${{ secrets.VAULT_ROLE_ID }}"
      VAULT_SECRET_ID: "${{ secrets.VAULT_SECRET_ID }}"

  deploy-to-staging:
    name: "Deploy"
    runs-on: "ubuntu-latest"
    needs:
      - "build-for-staging"
    steps:
      - name: "Checkout the code"
        uses: "actions/checkout@v2"
      - name: "Get build options"
        id: "get-build-options"
        uses: "./.gitea/actions/get-build-options"
      - name: "Get `backend` version"
        id: "get-backend-version"
        uses: "./.gitea/actions/get-service-version"
        with:
          service: "backend"
      - name: "Import Secrets"
        id: "import-secrets"
        uses: "hashicorp/vault-action@v2"
        with:
          url: "https://vault.bthlabs.pl/"
          method: "approle"
          roleId: "${{ secrets.VAULT_ROLE_ID }}"
          secretId: "${{ secrets.VAULT_SECRET_ID }}"
          secrets: |
            gitea/data/staging.hotpocket.app ansible_vault_payload | ANSIBLE_VAULT_PAYLOAD ;
            gitea/data/staging.hotpocket.app ansible_vault_password | ANSIBLE_VAULT_PASSWORD ;
            gitea/data/staging.hotpocket.app ansible_inventory_payload | ANSIBLE_INVENTORY_PAYLOAD ;
            gitea/data/staging.hotpocket.app ssh_key_payload | SSH_KEY_PAYLOAD
      - name: "Setup Ansible"
        uses: "./.gitea/actions/setup-ansible"
      - name: "Prepare Ansible secrets"
        run: |
          set -x

          mkdir deployment/hotpocket_app/.ci
          echo "${ANSIBLE_VAULT_PAYLOAD}" | base64 -d >"deployment/hotpocket_app/env_vars/staging/vault.yaml"
          echo "${ANSIBLE_VAULT_PASSWORD}" >"deployment/hotpocket_app/.ci/vault_password"
          echo "${ANSIBLE_INVENTORY_PAYLOAD}" | base64 -d >"deployment/hotpocket_app/inventory_ci.yaml"
          echo "${SSH_KEY_PAYLOAD}" | base64 -d >"deployment/hotpocket_app/.ci/ssh_key"
          chmod 600 deployment/hotpocket_app/.ci/ssh_key
      - name: "Engage!"
        env:
          VERSION: "${{ steps.get-backend-version.outputs.version }}"
          BUILD: "${{ steps.get-backend-version.outputs.build-number }}"
        run: |
          set -x

          (
            cd deployment/hotpocket_app ;
            ANSIBLE_HOST_KEY_CHECKING="False" /opt/ansible/bin/ansible-playbook \
              -i inventory_ci.yaml \
              --vault-id hotpocket@.ci/vault_password \
              -e @env_vars/staging/vars.yaml \
              -e @env_vars/staging/vault.yaml \
              -e hotpocket_app_image_tag="aio-${VERSION}-${BUILD}" \
              --limit "*.staging.hotpocket.app" \
              deploy.yaml
          )
