#!/usr/bin/env bash
set -e

script=$(basename "$0")
version="1.0.1"

help() {
    echo
    echo "$script"
    echo
    echo 'Description: Backup Grafana Dashboards from Url.'
    echo "Syntax: $script [-h|-c|-o|help]"
    echo 'Example: $script -h https://monitoring.example.com -k xxxxxxxxxxx -o tmp/erp.zip'
    echo 'options:'
    echo '  -u    Grafana endpoint url.'
    echo '  -t    API token.'
    echo '  -o    Output directory for the dashboard export files. Defaults to '\''/var/tmp'\''.'
    echo "  help  Show $script manual."
    echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit
fi

output=/var/tmp

while getopts ':u: :t: :o:' opt; do
    case $opt in
        u) url="$OPTARG";;
        t) token="$OPTARG";;
        o) output="$OPTARG";;
        \?) echo "Invalid option -$OPTARG" >&2
        help
        exit;;
    esac
done

[[ -z "$url" ]] && { echo 'Parameter -u|url is empty.' ; exit 1; }
[[ -z "$token" ]] && { echo 'Parameter -t|token is empty.' ; exit 1; }

mkdir -p "$output"

out=$(curl -s -H "Authorization: Bearer $token" -X GET $url/api/search?folderIds=0&query=&starred=false)
uids=$(echo $out | jq -r '.[] | .uid')
for id in $uids; do
    export_file="$output/grafana-dashboard-$id.json"
    curl -s -H "Authorization: Bearer $token" $url/api/dashboards/uid/$id | jq > $export_file
    echo "Dashboard with id $id exported to $export_file."
done
