#!/bin/bash

usage="./$(basename "$0") [-h/--help] [-p/--path <path>] [-j/--java_path <path>] [z/--zip_path <path>]

where:
    -h/--help       Show this help text. Optional.
    -p/--path       Path where jmeter is located. When used with zip path is used for unzip jmeter.
    -j/--java_path  Path to java when located on system. When not specified system java is used. Optional.
    -z/--zip_path   Path to zip file containing jmeter deployme"
    


# Set arguments
script_name=$(basename "$0")
short=:p:j:z:
long=path:,java_path:,zip_path:,help

# Init getopt with arguments
TEMP=$(getopt -o $short --long $long --name "$script_name" -- "$@")
eval set -- "${TEMP}"

# Init paths
HOME_PATH="~/jmeter-main2"
JAVA_PATH=""

# Parse arguments
while :; do
    case "${1}" in
    -j | --java_path) java_path=$2;
        if [[ ${java_path::1} == "-" ]]; then
                echo "$usage" >&2
                exit 1
        fi
        shift 2;;
    -p | --path) path=$2;
        if [[ ${path::1} == "-" ]]; then
                echo "$usage" >&2
                exit 1
        fi
        shift 2;;
    -z | --zip_path) zip_path=$2;
        if [[ ${zip_path::1} == "-" ]]; then
                echo "$usage" >&2
                exit 1
        fi
        shift 2;;
    -h | --help) echo "$usage" >&2; exit ;;
    --) shift; break ;;
    *) echo "$usage" >&2; exit ;;
    esac
done

if [[ $zip_path == "" && $path == "" ]]; then
    echo "$usage" >&2; exit ;
fi

if [[ $path != '' ]]; then
    HOME_PATH=$path
else
    mkdir -p ~/jmeter-main2
fi

if [[ $zip_path != "" ]]; then
    echo "Unziping file."
    eval cd $HOME_PATH
    unzip -q -o $zip_path
fi

if [[ $zip_path != "" ]]; then
    eval cd $HOME_PATH
    JAVA_PATH="${HOME_PATH}/$(cat java_version.txt)/"
elif [[ $java_path != '' ]]; then
    JAVA_PATH=$java_path
elif [[ -f $HOME_PATH/java_version.txt ]]; then
    eval cd $HOME_PATH
    JAVA_PATH="${HOME_PATH}/$(cat java_version.txt)/"
else
    JAVA_PATH=$(dirname $(dirname $(readlink -f $(which java))))
fi

eval "JAVA_HOME=${JAVA_PATH}" export JAVA_HOME

eval cd "${HOME_PATH}/jmeter/bin/"

sudo -E ./jmeter
