#!/usr/bin/env bash
################################################################################
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you 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.
################################################################################
#
# Generates OLM bundle from existing helm chart
#
#
set -euo pipefail

. env.sh
BASEDIR=$(dirname "$(realpath "$0")")
TARGET=${BASEDIR}/target
BUNDLE_VERSION=${BUNDLE_VERSION}
DOCKER_ORG=${DOCKER_ORG}
DOCKER_REGISTRY=${DOCKER_REGISTRY}
TAG=${IMAGE_TAG}

BUNDLE_IMG=${DOCKER_REGISTRY}/${DOCKER_ORG}/flink-op-bundle:${TAG}
BUNDLE=${TARGET}/${BUNDLE_VERSION}
CATALOG_IMG=${DOCKER_REGISTRY}/${DOCKER_ORG}/flink-op-catalog:${TAG}
CATDIR="${TARGET}/cat"
OLMTOOL_IMG="olm-utils"
CSV_TEMPLATE_DIR="${BASEDIR}/csv-template"

# Generate bundle in a docker container
generate_olm_bundle() {
  uid="$(id -u ${USER})"
  gid="$(id -g ${USER})"
  cp -r ../../helm ./
  docker build -t "${OLMTOOL_IMG}" -f utils.Dockerfile ${BASEDIR}
  docker run --user="${uid}:${gid}" -v ${BASEDIR}:/olm  "${OLMTOOL_IMG}"
  rm -rf helm
}

# Push bundle and catalog images for testing olm subscription
build_push_bundle(){
  docker build -f ${CSV_TEMPLATE_DIR}/bundle.Dockerfile -t "${BUNDLE_IMG}" ${BUNDLE}
  docker push "${BUNDLE_IMG}"
}
build_push_catalog(){
  docker build -f ${CSV_TEMPLATE_DIR}/catalog.Dockerfile -t ${CATALOG_IMG} ${CATDIR}
  docker push ${CATALOG_IMG}
}

# Simplest way to build local index(catalog) image without any upgrade path
# opm index add --bundles "${BUNDLE_IMG}" --tag "${CATALOG_IMG}" -c docker
# But we also want to test upgrade from the previus version
# Therefor, building local catalog image using latest file-based-catalog format
# https://olm.operatorframework.io/docs/reference/file-based-catalogs/#opm-generate-dockerfile
# We assume someone runing an older olm bundle.
# This enables testing upgrade from the previous version using startingCSV in Subscription
generate_fbc_config() {
rm -rf "${CATDIR}"
mkdir -p "${CATDIR}"
CATCONF="${CATDIR}/config.yaml"
OPM_IMAGE="quay.io/operator-framework/opm:latest"
cat <<EOF > "${CATCONF}"
---
defaultChannel: alpha
icon:
  base64data: [encoded data, 109136 characters]
  mediatype: image/svg+xml
name: flink-kubernetes-operator
schema: olm.package
---
name: alpha
package: flink-kubernetes-operator
schema: olm.channel
entries:
- name: flink-kubernetes-operator.v${PREVIOUS_BUNDLE_VERSION}
- name: flink-kubernetes-operator.v${BUNDLE_VERSION}
  replaces: flink-kubernetes-operator.v${PREVIOUS_BUNDLE_VERSION}
  skipRange: ">=1.0.1 <${BUNDLE_VERSION}"
EOF
  docker run ${OPM_IMAGE} render quay.io/operatorhubio/flink-kubernetes-operator:v${PREVIOUS_BUNDLE_VERSION} --output=yaml >> "${CATCONF}"
  docker run ${OPM_IMAGE} render ${BUNDLE_IMG} --output=yaml >> "${CATCONF}"
  docker run -v ${CATDIR}:/cat ${OPM_IMAGE} validate /cat
}

print_helper(){
echo "### First deploy the catalog server that serves the bundle"
echo "The OLM operator does not come with Kubernetes by default. To install OLM, run:"
echo "curl -sL https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.22.0/install.sh | bash -s v0.22.0"
echo "cat <<EOF | kubectl apply -f -
apiVersion: operators.coreos.com/v1alpha1
kind: CatalogSource
metadata:
  name: olm-flink-operator-catalog
  namespace: default
spec:
  sourceType: grpc
  image: "${DOCKER_REGISTRY}/${DOCKER_ORG}/flink-op-catalog:${TAG}"
EOF"

echo
echo "### After the catalog server is ready, create a subscription"
echo "cat <<EOF | kubectl apply -f -
apiVersion: operators.coreos.com/v1alpha2
kind: OperatorGroup
metadata:
  name: default-og
  namespace: default
spec:
  # if not set, default to watch all namespaces
  targetNamespaces:
  - default
---
apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
  name: flink-kubernetes-operator
  namespace: default
spec:
  channel: alpha
  name: flink-kubernetes-operator
  source: olm-flink-operator-catalog
  sourceNamespace: default
  # For testing upgrade from previous version
  #installPlanApproval: Automatic # Manual
  #startingCSV: "flink-kubernetes-operator.v${PREVIOUS_BUNDLE_VERSION}"
EOF"

echo
echo "After the operator is ready, deploy a flink job using:
kubectl create -f ../../examples/basic.yaml
or
kubectl create -f https://raw.githubusercontent.com/apache/flink-kubernetes-operator/release-$BUNDLE_VERSION/examples/basic.yaml
"


}
generate_olm_bundle
build_push_bundle

generate_fbc_config
build_push_catalog

print_helper
