#!/usr/bin/env bash

source "$(dirname "$0")/bash-prologue" ${BASH_SOURCE[0]} 'help,clean,debug-client:' 'hcd:' $* || exit $?

###########
# Arguments
###########

eval set -- $args

while [[ $1 != '--' ]]
do
    case $1 in
    -h|--help)
        usage; # does not return
        shift 1
        ;;
    -c|--clean)
        declare -r clean="clean"
        shift 1
        ;;
    -d|--debug-client)
        [[ -f "$d" ]] || error 1 "Debug client '$2' does not exist."
        declare -r debugClient="--debug-client '$2'"
        shift 2
        ;;
    esac
done

# TODO: Answer this: We like "splunk restart -f" because it's fast, but what's the right thing to do for customers?
# TODO: Do the right thing when SPLUNK_HOME is undefined
# TODO: Parameterize version number

declare -r appName="$(basename '${scriptRoot}')"
declare -r buildNumber=$(git log -1 --pretty=format:%ct)

[[ -z ${clean:-} ]] || rm -rf "$scriptRoot/build" "${SPLUNK_HOME}/etc/apps/${appName}"
"${scriptRoot}/setup.py" build --build-number="$buildNumber" ${debugClient:-}
splunk start ;# Because the splunk daemon might not be running
splunk install app "${scriptRoot}\build\${appName}-1.0.0-${buildNumber}.tar.gz" -auth admin:changeme -update 1
splunk restart -f ;# Because a restart is usually required after installing an application
