#!/bin/bash

source /var/onap/functions
source /var/onap/ccsdk

sdnc_src_folder=$git_src_folder/openecomp/sdnc
sdnc_repos=("sdnc/adaptors" "sdnc/architecture" "sdnc/core" "sdnc/features" \
"sdnc/northbound" "sdnc/oam" "sdnc/parent" "sdnc/plugins")

# clone_all_sdnc_repos() - Function that clones SDNC source repo.
function clone_all_sdnc_repos {
    for repo in ${sdnc_repos[@]}; do
        clone_repo $repo $sdnc_src_folder${repo#*sdnc}
    done
}

# compile_all_sdnc_repos() - Function that compiles SDNC source repo.
function compile_all_sdnc_repos {
    for repo in ${sdnc_repos[@]}; do
        if [[ "$repo" == "sdnc/core" ]]; then
            compile_src $sdnc_src_folder/core/rootpom
        fi
        compile_src $sdnc_src_folder${repo#*sdnc}
    done
}

# _build_sdnc_images() - Builds SDNC images from source code
function _build_sdnc_images {
    local folder=$sdnc_src_folder/oam

    get_ccsdk_images
    install_package unzip
    clone_repo sdnc/oam $folder
    # The OAM code depends on all the SDNC repos which should be downloaded and compiled first
    if [[ "$compile_repo" != "True" ]]; then
        compile_src $folder
    fi
    for dirc in ubuntu sdnc admportal dgbuilder; do
        build_docker_image $folder/installation/$dirc
    done
}

# get_sdnc_images() - Build or retrieve necessary images
function get_sdnc_images {
    if [[ "$build_image" == "True" ]]; then
        _build_sdnc_images
    else
        pull_openecomp_image sdnc-image openecomp/sdnc-image:latest
        pull_openecomp_image admportal-sdnc-image openecomp/admportal-sdnc-image:latest
        pull_openecomp_image dgbuilder-sdnc-image openecomp/dgbuilder-sdnc-image:latest
    fi
    pull_docker_image mysql/mysql-server:5.6
}

# install_sdnc() -  Download and install SDNC services from source code
function install_sdnc {
    clone_repo sdnc/oam $sdnc_src_folder/oam
    pushd $sdnc_src_folder/oam/installation/src/main/yaml
    install_docker_compose
    /opt/docker/docker-compose up -d
    popd
}

# init_sdnc() - Function that initialize SDNC services
function init_sdnc {
    if [[ "$clone_repo" == "True" ]]; then
        clone_all_sdnc_repos
        if [[ "$compile_repo" == "True" ]]; then
            compile_all_sdnc_repos
        fi
    fi

    if [[ "$skip_get_images" == "False" ]]; then
        get_sdnc_images
        if [[ "$skip_install" == "False" ]]; then
            start_ODL
            install_sdnc
        fi
    fi
}