name: Cleanup Yonote Docker registry
on:
  workflow_call:
    inputs:
      docker_repo_path:
        default: private.docker.wilix.dev
        required: false
        type: string
      docker_images_path:
        description: 'Относительный путь для образов проекта'
        required: true
        type: string
      werf_debug:
        default: false
        required: false
        type: boolean
      commit_sha:
        description: 'SHA текущего коммита'
        required: true
        type: string
    secrets:
      VAULT_ROLE_ID:
        required: true
      VAULT_SECRET_ID:
        required: true

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

jobs:
  cleanup:
    name: Cleanup
    runs-on: ubuntu-latest
    steps:
      - uses: https://github.com/actions/checkout@v3
      - name: Fetch all history for all tags and branches
        run: git fetch --prune --unshallow

      # 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: |
            ${{ env.vault_main_base_path }} local_cluster_kube_config_base64 ;
            ${{ env.vault_main_base_path }} docker_registry_username ;
            ${{ env.vault_main_base_path }} docker_registry_password ;
            dev/wilix/yonote/data/ci/yonote NPM_AUTH_TOKEN ;

      - name: Set COMMIT_SHA in environment
        run: echo "COMMIT_SHA=${{ inputs.commit_sha }}" >> "$GITHUB_ENV"
        
      - name: Login to wilix nexus Container Registry
        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: Setup debug if need
        if: ${{ inputs.werf_debug }}
        run: echo "WERF_LOG_DEBUG=true" >> "$GITHUB_ENV"

      - name: Cleanup
        run: werf cleanup
        env:
          WERF_REPO: ${{ inputs.docker_repo_path }}/${{ inputs.docker_images_path }}
          WERF_KUBECONFIG_BASE64: ${{ steps.import-secrets.outputs.local_cluster_kube_config_base64 }}
          NPM_AUTH_TOKEN: ${{ steps.import-secrets.outputs.NPM_AUTH_TOKEN }}
          COMMIT_SHA: ${{ inputs.commit_sha }}