name: Setup K8S Environment
description: Prepare the environment for A13labs CI/CD pipelines
inputs:
  access-token:
    description: "Bitwarden access token"
    required: true
  project-id:
    description: "Bitwarden project ID"
    required: true
  organization-id:
    description: "Bitwarden organization ID"
    required: true
  ansible-user:
    description: "The user to use for Ansible"
    required: true
  k8s-target:
    description: "The target host to deploy the K8S applications"
    default: "microk8s"
  ssh-auth-sock:
    description: "The SSH_AUTH_SOCK environment variable"
    default: "/tmp/ssh_agent.sock"

runs:
  using: "composite"
  steps:
    - name: Copy Kube Config from remote host
      shell: bash
      env:
        BW_ACCESS_TOKEN: ${{ inputs.access-token }}
        BW_PROJECT_ID: ${{ inputs.project-id }}
        BW_ORGANIZATION_ID: ${{ inputs.organization-id }}
        ANSIBLE_USER: ${{ inputs.ansible-user }}
        SSH_AUTH_SOCK: ${{ inputs.ssh-auth-sock }}
        K8S_TARGET: ${{ inputs.k8s-target }}
      run: |
        mkdir -p ~/.kube
        ansible -i inventory/hosts -u $ANSIBLE_USER -m fetch -a "src=/home/$ANSIBLE_USER/.kube/config dest=~/.kube/config flat=yes" $K8S_TARGET

    - name: Forward K8S API Server port
      shell: bash
      env:
        BW_ACCESS_TOKEN: ${{ inputs.access-token }}
        BW_PROJECT_ID: ${{ inputs.project-id }}
        BW_ORGANIZATION_ID: ${{ inputs.organization-id }}
        ANSIBLE_USER: ${{ inputs.ansible-user }}
        SSH_AUTH_SOCK: ${{ inputs.ssh-auth-sock }}
        K8S_TARGET: ${{ inputs.k8s-target }}
      run: |
        # Get Hostname and IP address of the target
        ANSIBLE_HOST=$(ansible -i inventory/hosts -u $ANSIBLE_USER -m shell -a "hostname" $K8S_TARGET | grep -oP '([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}' | head -1)
        IP_ADDR=$(ansible -i inventory/hosts -u $ANSIBLE_USER -m shell -a "curl -s ifconfig.me" $K8S_TARGET | grep -oP '(\d+\.){3}\d+')

        # Forward the k8s API server port to localhost
        ssh -f -N -L 16443:localhost:16443 "$ANSIBLE_USER@$ANSIBLE_HOST"

        # Override the kube config file to use localhost
        sed -i "s/server: https:\/\/$IP_ADDR:16443/server: https:\/\/localhost:16443/g" ~/.kube/config
