#!/bin/sh
##
# gget
# A script to get and install grafana versions
# for usage information see "show_help" below.
#

latest=$(wget -O - 'https://raw.githubusercontent.com/grafana/grafana/master/latest.json' | jq -r '.stable')
canary=$(wget -O - "https://grafana.com/api/grafana/versions" | jq ".items[0].version" | tr -d '"')

show_help() {
    echo "Usage: gget <version>"
    echo ""
    echo "where <version> can be:"
    echo "  1) A version from https://grafana.com/grafana/download (ex x.y.z)"
    echo "  2) latest (currently $latest)"
    echo "  3) canary (currently $canary)"
	echo ""
	echo "  -h, --help: Display this help message"
    echo ""
	exit 0
}

opts=$(getopt -o h --long help -n 'gget' -- "$@")
[ $? -eq 0 ] || {
	show_help
}

eval set -- "$opts"
while true; do
	case "$1" in
	-h | --help)
        show_help
		;;
	--)
		shift
		break
		;;
	*)
		break
		;;
	esac
	shift
done

[ -z "$1" ] && show_help

# Make sure the script is being run as root
if [ $EUID -ne 0 ]; then
  echo "This script must be run as root"
  exit 1
fi

##
# MAIN
#
# Enough setup, let's actually do something
#
version=$1
if [ "$version" == "latest" ]; then
  version="$latest"
  wget -O - "https://dl.grafana.com/oss/release/grafana-${version}.linux-amd64.tar.gz" | tar -C /opt -zxf -
elif [ "$version" == "canary" ]; then
  version="$canary"
  wget -O - "https://dl.grafana.com/oss/master/grafana-${version}.linux-amd64.tar.gz" | tar -C /opt -zxf -
else
  wget -O - "https://dl.grafana.com/oss/release/grafana-${version}.linux-amd64.tar.gz" | tar -C /opt -zxf -
fi

/bin/rm -rf /opt/grafana > /dev/null 2>&1 || true
ln -s /opt/grafana-${version} /opt/grafana

# nohup /opt/grafana/bin/grafana-server -config /opt/grafana/conf/defaults.ini -homepath /opt/grafana >/dev/null 2>&1 &