name: "Deploy stand by werf to kubernetes"
on:
  workflow_call:
    inputs:
      stand_name:
        description: 'Общее наименование стенда'
        required: true
        type: string
      kube_namespace:
        description: 'Местоположение для деплоя в кластере'
        required: true
        type: string
      docker_repo_path:
        default: private.docker.wilix.dev
        required: false
        type: string
      docker_images_path:
        description: 'Относительный путь для образов проекта'
        required: true
        type: string
      vault_secrets_base_path:
        description: 'Базовый путь для секретов проекта в vault'
        required: true
        type: string
      has_secrets:
        default: true
        required: false
        type: boolean
      werf_secret_key_vault_location:
        description: "Имя секрета, содержащего ключ для дешифрования werf, расположенного по базовому пути в vault"
        default: werf_secret_key
        required: false
        type: string
      notification_enabled:
        description: "Включение оповещений о разворачивании, требуется иметь url для оповещений в vault"
        default: true
        required: false
        type: boolean
      custom_notification_hook_enabled:
        description: "Использовать ли кастомный url хук для оповещений (должен лежать в vault секрете проекта)"
        default: false
        required: false
        type: boolean
      notification_channel:
        description: "Канал для оповещений о результатах деплоя"
        default: internal_projects_notifications
        required: false
        type: string
      werf_debug:
        default: false
        required: false
        type: boolean
    secrets:
      VAULT_ROLE_ID:
        required: true
      VAULT_SECRET_ID:
        required: true

env:
  vault_main_base_path: dev/wilix/main/data/ci

jobs:
  converge:
    name: Deploy stand
    runs-on: ubuntu-latest
    steps:

      - name: Checkout code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      # FIXME Эти секреты нужно будет сделать полностью различными для проектов, идеально - краткосрочные генерируемые vault
      - id: import-secrets
        uses: https://github.com/hashicorp/vault-action@v2
        with:
          url: https://vault.wilix.dev
          method: approle
          roleId: ${{ secrets.VAULT_ROLE_ID }}
          secretId: ${{ secrets.VAULT_SECRET_ID }}
          secrets: |
            dev/wilix/main/data/ci local_cluster_kube_config_base64 ;
            dev/wilix/main/data/ci docker_registry_username ;
            dev/wilix/main/data/ci docker_registry_password ;

      - name: Login to nexus docker
        uses: https://github.com/docker/login-action@v2
        with:
          registry: ${{ inputs.docker_repo_path }}
          username: ${{ steps.import-secrets.outputs.docker_registry_username }}
          password: ${{ steps.import-secrets.outputs.docker_registry_password }}

      - name: Install werf
        uses: https://github.com/werf/actions/install@v1.2

      - name: Add helm repositories
        run: |
          werf helm repo add wilix-dysnix https://artifacts.wilix.dev/repository/helm-dysnix
          werf helm repo add wilix-bitnami https://artifacts.wilix.dev/repository/helm-bitnami

      - name: Get werf secret key if need
        if: ${{ inputs.has_secrets }}
        uses: https://github.com/hashicorp/vault-action@v2
        with:
          url: https://vault.wilix.dev
          method: approle
          roleId: ${{ secrets.VAULT_ROLE_ID }}
          secretId: ${{ secrets.VAULT_SECRET_ID }}
          secrets: |
            ${{ inputs.vault_secrets_base_path }} ${{ inputs.werf_secret_key_vault_location }} | WERF_SECRET_KEY ;

      - name: Setup secrets if need
        if: ${{ inputs.has_secrets }}
        run: echo "WERF_SECRET_VALUES_STAND=.helm/secret-values-${{ inputs.stand_name }}.yaml" >> "$GITHUB_ENV"

      - name: Setup debug if need
        if: ${{ inputs.werf_debug }}
        run: echo "WERF_LOG_DEBUG=true" >> "$GITHUB_ENV"

      - name: Deploy
        run: werf converge
        env:
          WERF_ENV: ${{ inputs.stand_name }}
          WERF_VALUES_STAND: '.helm/values-${{ inputs.stand_name }}.yaml'
          WERF_NAMESPACE: ${{ inputs.kube_namespace }}
          WERF_REPO: ${{ inputs.docker_repo_path }}/${{ inputs.docker_images_path }}
          WERF_KUBECONFIG_BASE64: ${{ steps.import-secrets.outputs.local_cluster_kube_config_base64 }}

      - name: Get general notification url
        if: ${{ inputs.notification_enabled && ! inputs.custom_notification_hook_enabled && (job.status == 'success' || job.status == 'failure') }}
        uses: https://github.com/hashicorp/vault-action@v2
        with:
          url: https://vault.wilix.dev
          method: approle
          roleId: ${{ secrets.VAULT_ROLE_ID }}
          secretId: ${{ secrets.VAULT_SECRET_ID }}
          secrets: |
            ${{ env.vault_main_base_path }} notification_url | MATTERMOST_WEBHOOK_URL ;

      - name: Get custom notification url
        if: ${{ inputs.notification_enabled && inputs.custom_notification_hook_enabled && (job.status == 'success' || job.status == 'failure') }}
        uses: https://github.com/hashicorp/vault-action@v2
        with:
          url: https://vault.wilix.dev
          method: approle
          roleId: ${{ secrets.VAULT_ROLE_ID }}
          secretId: ${{ secrets.VAULT_SECRET_ID }}
          secrets: |
            ${{ inputs.vault_secrets_base_path }} notification_url | MATTERMOST_WEBHOOK_URL ;

      - name: prepare success notification body
        uses: https://github.com/finnp/create-file-action@master
        if: ${{ inputs.notification_enabled }}
        env:
          FILE_NAME: "mattermost.json"
          FILE_DATA: |
            {
              "channel": "${{ inputs.notification_channel }}",
              "attachments": [
                {
                  "fallback": "Деплой прошел успешно для ${{ gitea.repository }}",
                  "text": "Деплой прошел успешно для ${{ gitea.repository }} в ${{ inputs.stand_name }}",
                  "color": "#00FF00",
                  "fields": [
                    {
                      "short": true,
                      "title": "Сборка",
                      "value": "https://git.wilix.dev/${{ gitea.repository }}/actions/runs/${{ gitea.run_id }}"
                    }
                  ]
                }
              ]
            }

      - name: prepare failed notification body
        uses: https://github.com/finnp/create-file-action@master
        if: ${{ inputs.notification_enabled && failure() }}
        env:
          FILE_NAME: "mattermost.json"
          FILE_DATA: |
            {
              "channel": "${{ inputs.notification_channel }}",
              "attachments": [
                {
                  "fallback": "Деплой упал для ${{ gitea.repository }}",
                  "text": "Деплой упал для ${{ gitea.repository }} в ${{ inputs.stand_name }}",
                  "color": "#FF0000",
                  "fields": [
                    {
                      "short": true,
                      "title": "Сборка",
                      "value": "https://git.wilix.dev/${{ gitea.repository }}/actions/runs/${{ gitea.run_id }}"
                    }
                  ]
                }
              ]
            }

      - name: loop fail notification
        uses: https://github.com/mattermost/action-mattermost-notify@1.1.0
        if: ${{ inputs.notification_enabled && (job.status == 'success' || job.status == 'failure') }}