#!/usr/bin/env bash

debug() {
    >&2 echo "DEBUG: $@"
}

error() {
    >&2 echo "ERROR: $@"
    exit 1
}

install_rabbitmq_chart() {
    TEST_VALUES_DIR=$1
    ./helpers/deploy_rabbitmq.sh "${TEST_VALUES_DIR}" "${RELEASE_PREFIX}" || error "Failed to deploy rabbitmq"
}

install_postgis_chart() {
    TEST_VALUES_DIR=$1
    ./helpers/deploy_postgis.sh "${TEST_VALUES_DIR}" "${RELEASE_PREFIX}" || error "Failed to deploy postgis"
}

install_grb_chart() {
    TEST_VALUES_DIR=$1
    pushd geosphere-grb/chart
    sed -i "s/geosphere-rabbit-rabbitmq/${RABBITMQ_SERVICE_NAME}/g" "../../${TEST_VALUES_DIR}/values-grb-g16.yaml"
    helm upgrade -v 2 --install --namespace $ns -f ../../${TEST_VALUES_DIR}/values-grb-g16.yaml ${GRB_RELEASE_NAME} cspp-geo-grb/ || error "Failed to deploy GRB"
    popd
}

install_geo2grid_chart() {
    TEST_VALUES_DIR=$1
    grb_pvc=$(get_pvc_name ${GRB_RELEASE_NAME})
    sed -i "s/geosphere-rabbit-rabbitmq/${RABBITMQ_SERVICE_NAME}/g" "${TEST_VALUES_DIR}/values-geo2grid-g16-radm1.yaml"
    sed -i "s/cspp-geo-grb/${GRB_RELEASE_NAME}/g" "${TEST_VALUES_DIR}/values-geo2grid-g16-radm1.yaml"
    ./helpers/deploy_geo2grid.sh "${TEST_VALUES_DIR}" "${RELEASE_PREFIX}" "-g16-radm1" || error "Failed to deploy G2G"
}

install_tile_gen_chart() {
    TEST_VALUES_DIR=$1
    geotiff_pvc=$(get_pvc_name ${GEO2GRID_RELEASE_NAME})
    sed -i "s/geosphere-rabbit-rabbitmq/${RABBITMQ_SERVICE_NAME}/g" "${TEST_VALUES_DIR}/values-tile-gen-g16-radm1.yaml"
    sed -i "s/geosphere-postgis-postgresql/${POSTGIS_SERVICE_NAME}/g" "${TEST_VALUES_DIR}/values-tile-gen-g16-radm1.yaml"
    sed -i "s/cspp-geo-geo2grid/${GEO2GRID_RELEASE_NAME}/g" "${TEST_VALUES_DIR}/values-tile-gen-g16-radm1.yaml"
    ./helpers/deploy_tile_gen.sh "${TEST_VALUES_DIR}" "${RELEASE_PREFIX}" "-g16-radm1" || error "Failed to deploy tile gen"
}

install_mapserver_chart() {
    TEST_VALUES_DIR=$1
    sed -i "s/cspp-geo-geo2grid/${GEO2GRID_RELEASE_NAME}/g" "${TEST_VALUES_DIR}/values-mapserver.yaml"
    sed -i "s/geosphere-tile-gen-shapefiles/${TILEGEN_RELEASE_NAME}/g" "${TEST_VALUES_DIR}/values-mapserver.yaml"
    ./helpers/deploy_mapserver.sh "${TEST_VALUES_DIR}" "${RELEASE_PREFIX}" || error "Failed to deploy mapserver"
}


install_mapcache_chart() {
    TEST_VALUES_DIR=$1
    sed -i "s/geosphere-rabbit-rabbitmq/${RABBITMQ_SERVICE_NAME}/g" "${TEST_VALUES_DIR}/values-mapcache.yaml"
    sed -i "s/geosphere-postgis-postgresql/${POSTGIS_SERVICE_NAME}/g" "${TEST_VALUES_DIR}/values-mapcache.yaml"
    sed -i "s/geosphere-mapserver/${MAPSERVER_RELEASE_NAME}/g" "${TEST_VALUES_DIR}/values-mapcache.yaml"
    ./helpers/deploy_mapcache.sh "${TEST_VALUES_DIR}" "${RELEASE_PREFIX}" || error "Failed to deploy mapcache"
}

install_client_chart() {
    TEST_VALUES_DIR=$1
    sed -i "s/geosphere-mapserver/${MAPSERVER_RELEASE_NAME}/g" "${TEST_VALUES_DIR}/values-client.yaml"
    sed -i "s/geosphere-mapcache/${MAPCACHE_RELEASE_NAME}/g" "${TEST_VALUES_DIR}/values-client.yaml"
    ./helpers/deploy_client.sh "${TEST_VALUES_DIR}" "${RELEASE_PREFIX}" || error "Failed to deploy client"
}

get_pod_name() {
    release_name="$1"
    kubectl -n $ns get pods --selector=app.kubernetes.io/instance=${release_name} -o name
}

get_pvc_name() {
    release_name="$1"
    kubectl -n $ns get pvc --selector=app.kubernetes.io/instance=${release_name} -o name
}

wait_for_pod() {
    pod_name="$1"
    debug "Waiting for ${pod_name} pod to be ready..."
    kubectl -n $ns wait --for=condition=Ready ${pod_name} --timeout=120s
}

run_grb_checks() {
    count=0
    while true; do
      num_files=$(kubectl exec -n $ns ${GRB_POD_NAME} -c cspp-geo-grb-notifier -- ls -1 /dst | wc -l || echo 0)
      let count=count+1
      if [[ $num_files -gt 16 ]]; then
          debug "Got at least 16 files ($num_files)"
          break
      fi
      if [[ $count -gt 10 ]]; then
          error "Took too long for GRB to produce files ($num_files so far)"
      fi
      debug "Found $num_files files, waiting for more..."
      sleep 12
    done
}

run_geo2grid_checks() {
    count=0
    while true; do
      num_files=$(kubectl exec -n $ns ${GEO2GRID_POD_NAME} -- ls -1 /dst/geotiffs/g16/abi/radm1/ | wc -l || echo 0)
      let count=count+1
      if [[ $num_files -gt 16 ]]; then
          debug "Got at least 16 files ($num_files)"
          break
      fi
      if [[ $count -gt 10 ]]; then
          error "Took too long for Geo2Grid to produce files ($num_files so far)"
      fi
      debug "Found $num_files files, waiting for more..."
      sleep 12
    done
}

run_tile_gen_checks() {
    count=0
    while true; do
      num_files=$(kubectl exec -n $ns ${TILEGEN_POD_NAME} -- ls -1 /dst/tiles/g16/abi/radm1/C01/ | wc -l || echo 0)
      let count=count+1
      if [[ $num_files -gt 3 ]]; then
          debug "Got at least 3 files ($num_files)"
          break
      fi
      if [[ $count -gt 10 ]]; then
          error "Took too long for tile generation to produce its shape file"
      fi
      debug "Found $num_files files, waiting for more..."
      sleep 12
    done
    return 0
}

run_mapserver_checks() {
    # Ex: ["2020-11-24T22:23:19", "2020...
    # Get the first element without quotes
    first_time=$(curl -sS "http://${MAPSERVER_RELEASE_NAME}.${ns}/wms_times/g16/abi/radm1/C01" | head -c 21 | tail -c 19)
    debug "MapServer first time: ${first_time}"
    # if there aren't any times then we failed
    if [ $first_time == "" ]; then
        return 1
    else
        return 0
    fi
}

run_mapcache_checks() {
    first_time=$(curl -sS "http://${MAPSERVER_RELEASE_NAME}.${ns}/wms_times/g16/abi/radm1/C01" | head -c 21 | tail -c 19)
    debug "MapServer first time: ${first_time}"
    curl "http://${MAPCACHE_RELEASE_NAME}.${ns}/mapcache/wmts/?TIME=${first_time}Z&TILEMATRIXSET=grid_g16_abi_radf_1000m&LAYER=g16_abi_radf_l1b_C01&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix=0&TileCol=0&TileRow=0" >/dev/null
}

run_client_checks() {
    # just try to load the webpage at all
    curl "http://${CLIENT_RELEASE_NAME}.${ns}/" >/dev/null
}

check_and_uninstall() {
    ns="$1"
    release_name="$2"
    if [[ -z "${release_name}" ]]; then
        # the chart was never created
        debug "Release doesn't exist"
        return
    fi
    debug "Uninstalling ${release_name}"
    helm uninstall -n "${ns}" "${release_name}" || (debug "Could not uninstall chart $release_name" && return 1)
}

