#!/bin/bash

LOCAL_MAVEN_REPOSITORY=~/.m2/repository
OPERATOR_MAVEN_REPOSITORY=/tmp/artifacts/m2

kamel::description() {
    echo "Tools for developing integrations using Camel K"
}

kamel::usage() {
    cat <<EOT
    --sync-runtime          Synchronize runtime snapshot libraries with the camel k operator.
    --sync-lib              Synchronize snapshot libraries in the camel k operator (e.g. org/apache/camel/camel-activemq).

    --reset                 Reset the Camel K platform by deleting integration contexts and integrations

    --resync                Does a --sync-runtime followed by a --reset to restart all integrations with new libs

EOT
}


kamel::run() {
    source "$(basedir)/commands/util/openshift_funcs"
    source "$(basedir)/commands/util/camel_k_funcs"

    # Require oc
    command -v oc > /dev/null 2>&1 || { echo >&2 "ERROR: Command 'oc' not found. Please install it before proceeding.'"; exit 1; }

    if [ $(hasflag --sync-runtime) ]; then
        sync_runtime
    elif [ $(hasflag --sync-lib) ]; then
        sync_lib
    elif [ $(hasflag --reset) ]; then
        reset_camel_k
    elif [ $(hasflag --resync) ]; then
        sync_runtime
        reset_camel_k
        echo "Camel K platform resync completed."
    fi
}

sync_runtime() {
    local operator_pod=$(get_camel_k_operator_pod)

    for module in syndesis-parent common extension integration connector; do
        # Cannot filter because of https://bugzilla.redhat.com/show_bug.cgi?id=1559693
        sync_lib io/syndesis/$module $operator_pod
    done
}

sync_lib() {
    local libs=${1:-}
    local operator_pod=${2:-}

    local arg_modules=$(readopt --sync-lib);
    if [ -n "${arg_modules}" ]; then
        libs=${arg_modules//,/ }
    fi

    if [ -z "$operator_pod" ]; then
        operator_pod=$(get_camel_k_operator_pod)
    fi
    if [ -z "$operator_pod" ]; then
        echo "ERROR: Camel K Operator not found in current namespace."
        echo "Please install Camel K"
        exit 1
    fi

    for lib in $libs; do
        clean_lib=$(echo $lib | tr "." "/" | sed 's#/*$##;s#^/*##')
        parent_dir=$(echo $clean_lib | rev | cut -d'/' -f 2- | rev)

        oc exec $operator_pod -- mkdir -p $OPERATOR_MAVEN_REPOSITORY/$parent_dir
        oc rsync ~/.m2/repository/$clean_lib $operator_pod:$OPERATOR_MAVEN_REPOSITORY/$parent_dir
    done
}

get_camel_k_operator_pod() {
    oc get pod -l camel.apache.org/component=operator -o=jsonpath='{.items[0].metadata.name}' --ignore-not-found
}

reset_camel_k() {
    oc delete integrationcontext --all
    oc delete integration --all
}
