#!/usr/bin/env bash

indent() {
    local INDENT="      "
    sed -e "s/^/${INDENT}/" \
        -e "1s/^${INDENT}/${INDENT:0:-2}- /"
  }

listCSV() {
  for index in ${!CSVDIRS[*]}
  do
    cat $(ls ${CSVDIRS[$index]}/*version.yaml) | indent apiVersion
  done
}

CRDDIR=${DIR:-$(cd $(dirname "$0")/../deploy/crds && pwd)}
PKGDIR=${DIR:-$(cd $(dirname "$0")/../deploy/olm-catalog/openshift-pipelines-operator && pwd)}
CSVDIRS[0]=${DIR:-$(cd ${PKGDIR}/0.5.2 && pwd)}


NAME=${NAME:-openshift-pipelines-operator-registry}
NAMESPACE=${NAMESPACE:-openshift-operators}
x=( $(echo $NAME | tr '-' ' ') )
DISPLAYNAME=${DISPLAYNAME:=${x[*]^}}

CRD=$(cat $(ls $CRDDIR/*crd.yaml) | grep -v -- "---" | indent apiVersion)
PKG=$(cat $(ls $PKGDIR/*openshift-pipelines-operator.package.yaml) | indent packageName)

cat <<EOF | sed 's/^  *$//'
# This file was autogenerated by 'tektoncd-pipeline-operator/scripts/olm_catalog.sh'
# Do not edit it manually!
---
apiVersion: operators.coreos.com/v1alpha1
kind: CatalogSource
metadata:
  name: $NAME
  namespace: $NAMESPACE
spec:
  configMap: $NAME
  displayName: $DISPLAYNAME
  publisher: Red Hat
  sourceType: configmap
---
kind: ConfigMap
apiVersion: v1
metadata:
  name: $NAME
  namespace: $NAMESPACE
data:
  customResourceDefinitions: |-
$CRD
  clusterServiceVersions: |-
$(listCSV)
  packages: |-
$PKG
EOF
