#! /usr/bin/env bash
# HOW TO USE: Put this file inside the directory where you would like to extract and run the product-APIM build file (.zip file)
# Change the below path variables accordingly *** NOTE: No trailing `/` slashes has been used
# This will only work with APIM 3.0.0 latest version with Carbon 4.x kernel. Addition to coping and unziping the pack,
# This script will only create symbolic links to the carbon-apimgt repository files.
source_path="/Users/tmkasun/Documents/wso2/dev/products/apim/carbon-apimgt-forked/features/apimgt"
product_apimgt_path="/Users/tmkasun/Documents/wso2/dev/products/apim/product-apim-forked"
pack_name="wso2am-3.0.0-SNAPSHOT"

action=$1


create_symlink() {
    sources=$1
	destination=$2
	mv $destination "${destination}_back"
    echo "Linking " "${sources}" " ==========> " "${destination}"
    # mkdir -p `pwd`"/${destination}"
    #sudo mount --bind "${sources}" `pwd`"/${destination}"
    ln -s "${sources}" "${destination}"
}

symlink_apps() {
    artifact_id=$1
    dir_name=$2
    alt_dir_name=$3
    source="${source_path}/${artifact_id}/src/main/resources/${dir_name}"
    if [ $alt_dir_name ]
        then
            echo "Mapping $dir_name in source to $alt_dir_name in pack . . ."
            dir_name=$alt_dir_name
    fi
    create_symlink "${source}" "${pack_name}/repository/deployment/server/jaggeryapps/${dir_name}"

}

run() {
    echo "Running the setup ..."

    echo "Starting APIM ..."
    ./${pack_name}/bin/wso2server.sh
}

checkExitCode() {
    exit_code=$?; if [[ $exit_code != 0 ]]; then exit $exit_code; fi
}

setup() {
    echo "Setting-up the environment ..."
    echo "coping ${pack_name}zip from product apimgt build path to here ..."
    cp "${product_apimgt_path}/modules/distribution/product/target/${pack_name}.zip" .
    checkExitCode

    echo "Removing existing  $pack_name"
    rm -R ${pack_name}

    echo "Unziping $pack_name"
    code=$(unzip "${pack_name}.zip")
    checkExitCode

    echo "Creating symlinks for Publisher ..."
    symlink_apps "org.wso2.carbon.apimgt.publisher.feature" "publisher"
    checkExitCode

    echo "Creating symlinks for Store ..."
    symlink_apps "org.wso2.carbon.apimgt.store.feature" "devportal"
    checkExitCode

    run
}


if [ "$action" == "setup" ]; then
   setup
elif [ "$action" == "run" ]; then
   run
else
   echo "Unknown parameter. Type either 'setup' or 'run'"
fi

exit 1