#!/bin/bash -ex

echo "render_templates START..."

rm -rf src

source include/ocs.sh
export OCS_VERSION=$(echo $CPAAS_PRODUCT_VERSION | cut -d'.' -f -2)

# Install golang 1.16, from include/ocs.sh
get_golang_1_16

# Install oc, from include/ocs.sh
get_oc_tool

# Get the ocs-operator sources for the commit
git clone "https://github.com/red-hat-storage/ocs-operator" src

pushd src

git reset --hard "4181add3ccec34e91bfab019c333aa73657744dc"
git clean -fxd

# override some code from github by modified scripts from midstream
cp -r ../cpaas-ocs-bundle-scripts/* ./

# Login to RH registry for getting info about sidecar images with a service account
skopeo login --authfile .skopeo-auth.json -u '6340056|ocs-cpaas' -p 'eyJhbGciOiJSUzUxMiJ9.eyJzdWIiOiJhNDAzMTM3MTdiZGE0ODYxOTVlZTI1ZTQwZDcwM2QxMyJ9.VhReKSe542C8xjlRV3fkGF0DeN6t24YBjnbmn_9u9togxhxb5MBqlF3yZgay7TVFZzFqaiXk3fHzIAv39HHIjaC-LFED7RF63mCBpF-7T8Y4Yvr7NpcEDCi_GHrUB_369tb61N85CVQPloEN8JGuQuzMGV0itfCP8MA20kRj9Us9b8C2wOLl6z6SdU0P2BBLkwkhdypmnkp--FerEgcTj2BN3kZxsR7h_v52naEv9UXGospr-QPwUBHEu4W06BtJu_WFqz8xJWmVSiSSvpLRs0_dI0XtavVys2_jzqPgS6eY7UBXlJ2CX6t8oRoOoaum-PuxeqNG-KuKn2ntLJyrKgau8gGLloToFODu021K6kJYNc706VZ7Y98lkfME3inbq8MgM0C-FYvy2tvc-ji4vtzasynsHXaZmwBrg0aJcskbG8FG5r0BLUpzAFcie69G_Ya2DsVKy72MicFjCxkuciQB0CUaJMx1H-sXD7iqVU0CCi09gGfO4DYsLOadg1JOrwwh-EvYWCdbGRh3uyPAtVP2zLMWCkdiDJQVhFlQGU9Aw9ffxx_UhNRpJBgLmb_ANJZnrvEu7etPnz0cUHs32HYT23wlR4e10hgqSsem7Xpucb_xpYGkOa8pUnVS2k45rCkhToaVWDZ10R4ASz8pwRnmbUHiyTfJ03nwWA-Ni1Y' registry.redhat.io

# Set rhceph image
CEPH_IMAGE=$(tag_to_sha "${SIDECAR_MAP[rhceph]}")

# Fix final ceph image location
export CEPH_IMAGE=${CEPH_IMAGE/registry-proxy.engineering.redhat.com\/rh-osbs\/rhceph/registry.redhat.io\/rhceph\/rhceph-5-rhel8}

export ROOK_IMAGE=$(tag_to_sha ${ROOK_CEPH_OPERATOR_IMAGE_PULL_URL})
export NOOBAA_IMAGE=$(tag_to_sha ${NOOBAA_OPERATOR_IMAGE_PULL_URL})
export VOLUME_REPLICATION_OPERATOR_IMAGE=$(tag_to_sha ${VOLUME_REPLICATION_OPERATOR_IMAGE_PULL_URL})

## Set container version and release
# Version copies supplied CSV version
VERSION="${CPAAS_PRODUCT_VERSION}"

# Overwrite CSV version for CSV generation
export CSV_VERSION="${CPAAS_PRODUCT_VERSION}"
export OCS_IMAGE=$(tag_to_sha ${OCS_OPERATOR_IMAGE_PULL_URL})
export OCS_MUST_GATHER_IMAGE=$(tag_to_sha ${OCS_MUST_GATHER_IMAGE_PULL_URL})
export ROOK_CSI_CEPH_IMAGE=$(tag_to_sha ${CEPHCSI_IMAGE_PULL_URL})

# Set CSI sidecar images
export ROOK_CSI_REGISTRAR_IMAGE=$(tag_to_sha "${SIDECAR_MAP[csi-node-driver-registrar]}")
export ROOK_CSI_RESIZER_IMAGE=$(tag_to_sha "${SIDECAR_MAP[csi-external-resizer]}")
export ROOK_CSI_PROVISIONER_IMAGE=$(tag_to_sha "${SIDECAR_MAP[csi-external-provisioner]}")
export ROOK_CSI_ATTACHER_IMAGE=$(tag_to_sha "${SIDECAR_MAP[csi-external-attacher]}")
export ROOK_CSI_SNAPSHOTTER_IMAGE=$(tag_to_sha "${SIDECAR_MAP[csi-external-snapshotter]}")

# Override noobaa images
export NOOBAA_CORE_IMAGE=$(tag_to_sha ${NOOBAA_CORE_IMAGE_PULL_URL})
export NOOBAA_DB_IMAGE=$(tag_to_sha "${SIDECAR_MAP[noobaa-db]}")

# this range should allow any older version to be upgraded to this version
# see: https://github.com/operator-framework/operator-lifecycle-manager/blob/release-4.2/doc/design/how-to-update-operators.md#skiprange
export SKIP_RANGE=">=4.2.0 <${CSV_VERSION}"
# Set replaces to unmask older builds in OLM
CSV_Z_VERSION=$(echo "${CPAAS_PRODUCT_VERSION}" | cut -d '.' -f 3)
if test "$CSV_Z_VERSION" -gt 0; then
        export REPLACES_CSV_VERSION="$OCS_VERSION.$(($CSV_Z_VERSION - 1))"
fi

# Generate release CSV
make gen-release-csv

#Logout from RH registry
skopeo logout --authfile .skopeo-auth.json registry.redhat.io

popd

### Modify manifests ###
# Remove old manifests dir
rm -rf bundle
mkdir bundle

# Get release number
RELEASE=$(cat Dockerfile|egrep -e 'release="' | sed -e 's|^.*release="\(.*\)".*$|\1|')

## The release number magic
# Bump the release field if uncommented, uncomment release field without bumping it if commented out
sed -i -e "s|^LABEL release=.*\$|LABEL release=\"$((RELEASE+1))\"|" Dockerfile
sed -i -e "s|^#LABEL release=.*\$|LABEL release=\"$RELEASE\"|" Dockerfile

# Get an actual current release to update full_version properly
RELEASE=$(cat Dockerfile|egrep -e 'release="' | sed -e 's|^.*release="\(.*\)".*$|\1|')

# Copy the new manifests and metadata to dist-git
cp -a src/deploy/bundle/manifests/ ./bundle
cp -a src/deploy/bundle/metadata/ ./bundle

# Add ocs-operator, noobaa-core and noobaa-db to the bundle (if missing)
sed -ne '/^  relatedImages:$/,$ p' bundle/manifests/ocs-operator.clusterserviceversion.yaml | grep -q "$OCS_IMAGE" || sed -i "/^  relatedImages:\$/a\  - image: $OCS_IMAGE\n    name: ocs-operator" bundle/manifests/ocs-operator.clusterserviceversion.yaml
sed -ne '/^  relatedImages:$/,$ p' bundle/manifests/ocs-operator.clusterserviceversion.yaml | grep -q "$NOOBAA_CORE_IMAGE" || sed -i "/^  relatedImages:\$/a\  - image: $NOOBAA_CORE_IMAGE\n    name: noobaa-core" bundle/manifests/ocs-operator.clusterserviceversion.yaml
sed -ne '/^  relatedImages:$/,$ p' bundle/manifests/ocs-operator.clusterserviceversion.yaml | grep -q "$NOOBAA_DB_IMAGE" || sed -i "/^  relatedImages:\$/a\  - image: $NOOBAA_DB_IMAGE\n    name: noobaa-db" bundle/manifests/ocs-operator.clusterserviceversion.yaml

# Add the full_version label for QE to be able to identify the build
sed -i "/^  labels:\$/a\    full_version: $CPAAS_PRODUCT_VERSION-$RELEASE" bundle/manifests/ocs-operator.clusterserviceversion.yaml

# Update the example ocs-operator image
sed -i "s|quay.io/ocs-dev/ocs-operator:.*\$|$OCS_IMAGE|g" bundle/manifests/ocs-operator.clusterserviceversion.yaml

# Only set the default channel for the X.Y.0 builds
CSV_Z_VERSION=$(echo "${CSV_VERSION}" | cut -d '.' -f 3)
if test "$CSV_Z_VERSION" -eq 0; then
        # Update the default channel
        sed -i -e "s|^.*LABEL operators.operatorframework.io.bundle.channel.default.v1=.*$|LABEL operators.operatorframework.io.bundle.channel.default.v1=stable-${OCS_VERSION}|" Dockerfile
        sed -i -e "s|^.*operators.operatorframework.io.bundle.channel.default.v1:.*$|  operators.operatorframework.io.bundle.channel.default.v1: \"stable-${OCS_VERSION}\"|" bundle/metadata/annotations.yaml
else
        # Comment out the default channel
        sed -i -e "s|^.*LABEL operators.operatorframework.io.bundle.channel.default.v1=.*$|#LABEL operators.operatorframework.io.bundle.channel.default.v1=stable-${OCS_VERSION}|" Dockerfile
        sed -i -e "s|^.*operators.operatorframework.io.bundle.channel.default.v1:.*$|  #operators.operatorframework.io.bundle.channel.default.v1: \"stable-${OCS_VERSION}\"|" bundle/metadata/annotations.yaml
fi

sed -i -e "s|^.*operators.operatorframework.io.bundle.channels.v1:.*$|  operators.operatorframework.io.bundle.channels.v1: \"stable-${OCS_VERSION}\"|" bundle/metadata/annotations.yaml
sed -i -e "s|^.*operators.operatorframework.io.bundle.package.v1:.*$|  operators.operatorframework.io.bundle.package.v1: ocs-operator|" bundle/metadata/annotations.yaml

# Update versions of dependencies if they exist
if test -e bundle/metadata/dependencies.yaml; then
        sed -i -e "s/version: .*/version: \"<$OCS_VERSION.0 || $VERSION\"/g" bundle/metadata/dependencies.yaml
fi

rm -rf src
