{{ if .Values.pipelines.deployableResources.tasks }}
apiVersion: tekton.dev/v1
kind: Task
metadata:
  name: gerrit-ssh-cmd
  labels:
    {{- include "edp-tekton.labels" . | nindent 4 }}
  annotations:
    tekton.dev/pipelines.minVersion: "0.12.1"
    tekton.dev/categories: Gerrit Tools
    tekton.dev/tags: ssh, gerrit api
    tekton.dev/displayName: "gerrit api over ssh"
    tekton.dev/platforms: "linux/amd64"
spec:
  description: >-
    The following task can be used to run gerrit votes using ssh.

    The following task takes gerrit host and required credentials as input along
    with the command and run it on gerrit server.
  workspaces:
    - name: ssh-directory
      optional: true
      description: |
        A .ssh directory with private key, known_hosts, config, etc. Copied to
        the user's home before ssh commands are executed.
  params:
    - name: GERRIT_HOST
      type: string
      description: Remote host to connect
      default: "gerrit"
    - name: USERNAME
      type: string
      description: SSH username
      default: "edp-ci"
    - name: GERRIT_PORT
      type: string
      description: SSH port, default is 22
      default: "22"
    - name: SSH_GERRIT_COMMAND
      type: string
      description: The gerrit command you want to run over ssh
    - name: ERR_EXIT_CODE
      type: string
      description: Define Error exit code for task. By default - 1. In case of skip set 0
      default: "1"
    - name: userHome
      description: |
        Absolute path to the user's home directory. Set this explicitly if you are running the image as a non-root user or have overridden
        the gitInitImage param with an image containing custom user configuration.
      type: string
      default: "/tekton/home"
  steps:
    - name: ssh
      image: '{{ include "edp-tekton.registry" . }}/epamedp/tekton-openssh-client:0.1.5'
      env:
        - name: GERRIT_HOST
          value: "$(params.GERRIT_HOST)"
        - name: GERRIT_PORT
          value: "$(params.GERRIT_PORT)"
        - name: USERNAME
          value: "$(params.USERNAME)"
        - name: SSH_GERRIT_COMMAND
          value: "$(params.SSH_GERRIT_COMMAND)"
        - name: PARAM_USER_HOME
          value: $(params.userHome)
        - name: ERR_EXIT_CODE
          value: $(params.ERR_EXIT_CODE)
        - name: WORKSPACE_SSH_DIRECTORY_BOUND
          value: $(workspaces.ssh-directory.bound)
        - name: WORKSPACE_SSH_DIRECTORY_PATH
          value: $(workspaces.ssh-directory.path)
      script: |
        #!/usr/bin/env sh
        set -eu

        if [ "${WORKSPACE_SSH_DIRECTORY_BOUND}" = "true" ] ; then
          cp -R "${WORKSPACE_SSH_DIRECTORY_PATH}" "${PARAM_USER_HOME}"/.ssh
          chmod 700 "${PARAM_USER_HOME}"/.ssh
          chmod -R 400 "${PARAM_USER_HOME}"/.ssh/*
        fi

        ssh -o StrictHostKeyChecking=no -p ${GERRIT_PORT} ${USERNAME}@${GERRIT_HOST} gerrit ${SSH_GERRIT_COMMAND} || exit ${ERR_EXIT_CODE}
{{ end }}
