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

latest=$(curl -s 'https://raw.githubusercontent.com/grafana/grafana/master/latest.json' | jq -r '.stable')
canary=$(curl -s "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
[ "$version" == "latest" ] && version="$latest"
[ "$version" == "canary" ] && version="$canary"
wget "https://dl.grafana.com/oss/release/grafana_${version}_amd64.deb" -O "/tmp/grafana_${version}_amd64.deb"
dpkg -i "/tmp/grafana_${version}_amd64.deb" && /bin/rm -rfv "/tmp/grafana_${version}_amd64.deb"
