#!/usr/bin/env bash
set -e

# https://access.redhat.com/articles/6047221

oc version
oc config current-context

operator_subscription_yaml='
apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
    name: gatekeeper-operator-product
    namespace: openshift-operators
spec:
    channel: stable
    installPlanApproval: Automatic
    name: gatekeeper-operator-product
    source: redhat-operators
    sourceNamespace: openshift-marketplace
'

echo "$operator_subscription_yaml" | oc apply --dry-run=client -f -
echo "$operator_subscription_yaml" | oc apply --dry-run=server -f -
echo "$operator_subscription_yaml" | oc apply -f -

# Need to wait for the gatekeeper-operator to create the gatekeeper object
while true; do
    oc get crd/gatekeepers.operator.gatekeeper.sh && break
    sleep 5
done

operator_gatekeeper_yaml='
apiVersion: operator.gatekeeper.sh/v1alpha1
kind: Gatekeeper
metadata:
    name: gatekeeper
spec:
    validatingWebhook: Enabled
    webhook:
        logLevel: DEBUG
        replicas: 1
    audit:
        # https://open-policy-agent.github.io/gatekeeper/website/docs/audit/#configuring-audit
        # https://github.com/gatekeeper/gatekeeper-operator/blob/main/config/samples/gatekeeper_with_all_values.yaml

        replicas: 1
        logLevel: DEBUG

        # OOMKilled - OPA Gatekeeper Audit
        # See https://github.com/open-policy-agent/gatekeeper/issues/1630
        auditFromCache: Disabled

        auditInterval: 600s
        constraintViolationLimit: 20
        auditChunkSize: 50

        resources:
            # Defaults are:
            #  requests:
            #      cpu: 100m
            #      memory: 256Mi
            #  limits:
            #      cpu: 1
            #      memory: 512Mi

            requests:
                cpu: 100m
                memory: 512Mi
            limits:
                cpu: 1
                memory: 1024Mi
'

echo "$operator_gatekeeper_yaml" | oc apply --dry-run=client -f -
echo "$operator_gatekeeper_yaml" | oc apply --dry-run=server -f -
echo "$operator_gatekeeper_yaml" | oc apply -f -

# Need to wait for the gatekeeper to create the config crd...
while true; do
    oc -n openshift-gatekeeper-system get crd/configs.config.gatekeeper.sh && break
    sleep 5
done

operator_config_yaml='
---
apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata:
    name: config
    namespace: openshift-gatekeeper-system
spec:
    match:
        # https://open-policy-agent.github.io/gatekeeper/website/docs/exempt-namespaces/
        - excludedNamespaces: ["default", "kube*", "openshift*"]
          processes: ["*"]
'

echo "$operator_config_yaml" | oc apply --dry-run=client -f -
echo "$operator_config_yaml" | oc apply --dry-run=server -f -
echo "$operator_config_yaml" | oc apply -f -
