---
version: "3"

tasks:
  cleanup-pods:
    desc: Clean up leftover Pods
    cmds:
      - for:
          matrix:
            PHASE: [Failed, Succeeded, Pending]
        cmd: kubectl delete pods --field-selector status.phase={{.ITEM.PHASE}} -A --ignore-not-found=true
  sync-secrets:
    desc: Sync ExternalSecret resources
    vars:
      secret: '{{ .secret | default ""}}'
      namespace: '{{.namespace | default "default"}}'
    cmd: |
      {{if eq .secret ""}}
        kubectl get externalsecret.external-secrets.io --all-namespaces --no-headers -A | awk '{print $1, $2}' \
          | xargs --max-procs=4 -l bash -c 'kubectl -n $0 annotate externalsecret.external-secrets.io $1 force-sync=$(date +%s) --overwrite'
      {{else}}
        kubectl -n {{.namespace}} annotate externalsecret.external-secrets.io {{.secret}} force-sync=$(date +%s) --overwrite
      {{end}}
    preconditions:
      - kubectl -n {{.namespace}} get externalsecret {{.secret}}
  mount-volume:
    desc: Mount a PersistentVolumeClaim to a temporary pod
    interactive: true
    vars:
      claim: '{{ or .claim (fail "PersistentVolumeClaim `claim` is required") }}'
      namespace: '{{.namespace | default "default"}}'
    cmd: |
      kubectl run -n {{.namespace}} debug-{{.claim}} -i --tty --rm --image=null --privileged --overrides='
        {
          "apiVersion": "v1",
          "spec": {
            "containers": [
              {
                "name": "debug",
                "image": "docker.io/library/alpine:latest",
                "command": ["/bin/ash"],
                "stdin": true,
                "stdinOnce": true,
                "tty": true,
                "volumeMounts": [
                  {
                    "name": "config",
                    "mountPath": "/config"
                  }
                ]
              }
            ],
            "volumes": [
              {
                "name": "config",
                "persistentVolumeClaim": {
                  "claimName": "{{.claim}}"
                }
              }
            ],
            "restartPolicy": "Never"
          }
        }'
    preconditions:
      - kubectl -n {{.namespace}} get pvc {{.claim}}