# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO: Setup a conditional for idempotency (does this already exist?)
- name: "Test for External Secrets secret"
  include: kubectl-presence.yaml
  vars:
    name: "gcp-store-creds"
    type: "secrets"
    namespace: "external-secrets"
    kubeconfig: "{{ kubeconfig_shared_location }}"
    fact_name: "has_es_secret"
  when:
    - (primary_cluster_machine is defined)
    - (primary_cluster_machine == true)
  tags:
  - external-secrets-operator
  - external-secrets

- name: "Create secret for External Secrets"
  shell: |
    kubectl create ns external-secrets || true
    kubectl create secret generic gcp-store-creds --from-file=/var/keys/external-secrets-k8s-creds.json -n external-secrets || true
    kubectl label secret gcp-store-creds -n external-secrets type=gcpsm --overwrite
  ignore_errors: yes
  environment:
    KUBECONFIG: "{{ kubeconfig_shared_location }}"
  when:
    - (primary_cluster_machine is defined)
    - (primary_cluster_machine == true)
    - (has_es_secret == false)
  tags:
  - external-secrets-secret
  - external-secrets

- name: Create folder for External Secrets files
  file:
    path: '{{ external_secrets_files }}'
    state: directory
    mode: '0755'
  tags:
  - external-secrets-operator
  - external-secrets

# Copy over the external secrets operator and CRD to all inventory
- name: Copy External Secrets Operator and CRD files
  copy:
    src: "{{ item }}"
    dest: "{{ external_secrets_files }}"
    mode: '0444' # read/write/execute owner, everyone else read/execute
  with_fileglob: "external-secrets-c*.yaml"
  tags:
  - external-secrets-operator
  - external-secrets

## TODO: Move this to Pull repository?  Chicken/egg issue...no CRD, so cannot apply...SecretStore requires project ID to be injected (perhaps move to workload identity?)
- name: Copy Secrets Manager Store
  template:
    src: external-secrets-store.yaml.j2
    dest: "{{ external_secrets_files }}/external-secrets-store.yaml"
  when:
    - (primary_cluster_machine is defined)
    - (primary_cluster_machine == true)
  tags:
  - external-secrets
  - external-secrets-store

