#!/bin/bash

# This script fetches Datadog dashboards, monitors, and metric metadata for a given account
# Results are saved to the datadog from your current working directory

# To fetch everything for an account pass `-all [dashboards|monitors|metrics]`
# Results are saved to datadog/[dashboards|monitors]/[dashboards|monitors|metrics].json


# To fetch a subset of resources pass `[dashboard|monitor|metrics]-ids` with a list of ids
# Each resource is saved in a file named $ID.json in datadog/[dashboards|monitors|metrics]/


declare -a items
DASHBOARD_URL="https://api.datadoghq.com/api/v1/dashboard"
MONITOR_URL="https://api.datadoghq.com/api/v1/monitor"
METRIC_URL="https://api.datadoghq.com/api/v1/metrics"
EXPORT_DIR="datadog"

function preflight {
  if [ -z "$DD_CLIENT_APP_KEY" ]
  then
    echo "Must set DD_CLIENT_APP_KEY. Create one here: https://app.datadoghq.com/account/settings#api"
    exit 1
  fi

  if [ -z "$DD_CLIENT_API_KEY" ]
  then
    echo "Must set DD_CLIENT_API_KEY. Create one here: https://app.datadoghq.com/account/settings#api"
    exit 1
  fi

  status_code=$(curl -w %{http_code} --silent -o /dev/null -X GET https://api.datadoghq.com/api/v1/validate \
  -H "Content-Type: application/json" \
  -H "DD-API-KEY: ${DD_CLIENT_API_KEY}")

  if [[ "$status_code" -ne 200 ]]
  then
    echo "Invalid API key."
    exit 1
  fi

  echo $'preflight checks passed\n'
}

function call_api {
  url=$1
  export_file=$2

  status_code=$(curl -w %{http_code}  --silent -o $export_file -X GET "$url" \
    -H "Content-Type: application/json" \
    -H "DD-API-KEY: ${DD_CLIENT_API_KEY}" \
    -H "DD-APPLICATION-KEY: ${DD_CLIENT_APP_KEY}")

  if [[ "$status_code" -ne 200 ]]
  then
    echo "Request failed"
    echo $status_code
    exit 1
  fi
}

function get_all {
  item=$1
  echo "fetching all ${item}...."

  dir=${EXPORT_DIR}/${item}
  export_file=${dir}/${item}.json

  if [ ! -d $dir ]
  then
    mkdir -p -m777 $dir
  fi

  if [ "$item" = "dashboards" ]
  then
    url=$DASHBOARD_URL
    call_api $url $export_file
    parse_ids $export_file
    for id in "${items[@]}";
      do get_by_id $item $id;
    done;
  elif [ "$item" = "monitors" ]
  then
    url=$MONITOR_URL
    call_api $url $export_file
  elif [ "$item" = "metrics" ]
  then
    url=$METRIC_URL
    get_all_active_metrics
    parse_metrics $export_file
    for m in "${metrics[@]}"
    do
      get_by_id $item $m
    done
  fi

  echo "Success! All ${item} exported."
}

function parse_metrics {
    # trims response to only metric names
    cut=$(cat ./datadog/metrics/metrics.json | awk -F '[][]' '{print $2}' | tr -d "\"")
    IFS=","
    read -a metrics <<< "$cut"
}

function parse_ids() {
  echo "parsing ..."
  export_file=$1
  tmp=$(cat ${export_file} | grep -o '"id":"\([^"]*\)"' | cut -d ":" -f 2 | tr -d '"' )
  items=(${tmp})
  }

function get_by_id {
  item=$1
  id=$2
  dir=${EXPORT_DIR}/${item}
  export_file=${dir}/${id}.json

  if [ ! -d $dir ]
  then
    mkdir -p -m777 $dir
  fi

  if [ "$item" = "dashboards" ]
  then
    url=$DASHBOARD_URL/$id
  elif [ "$item" = "monitors" ]
  then
    url=$MONITOR_URL/$id
  elif [ "$item" = "metrics" ]
  then
    url=$METRIC_URL/$id
  else
    echo "$item is an unsupported type. Only dashboards, monitors, and metrics are supported."
    exit 1
  fi
  call_api $url $export_file
  echo "Success! $item written to $export_file"
}


function get_all_active_metrics {
    echo $url
    now_epoch=$(date +%s)
    two_weeks_in_seconds=1209600
    from=$(($now_epoch-$two_weeks_in_seconds))

    if [ ! -d $dir ]
      then
        mkdir -p -m777 $dir
    fi

    from_query="?from=${from}"
    echo $from_query
    url=$url$from_query

    call_api $url $export_file
}

preflight

if [ ! -d $EXPORT_DIR ]
then
  mkdir -p -m777 $EXPORT_DIR
fi


while [[ $# -gt 0 ]]
do
  key="$1"

case $key in
 -all)
   type=$2
   get_all $type
   exit 0;;
 -monitor-ids)
  input=$2
  IFS=','
  read -ra ids <<< "$input"
  for id in "${ids[@]}"; do
    get_by_id "monitors" $id
  done
  exit 0;;
  -dashboard-ids)
  input=$2
  IFS=','
  read -ra ids <<< "$input"
  for id in "${ids[@]}"; do
    get_by_id "dashboards" $id
  done;
  exit 0;;
  -metric-ids)
  input=$2
  IFS=','
  read -ra ids <<< "$input"
  for id in "${ids[@]}"; do
    get_by_id "metrics" $id
  done;
  exit 0;;
  *)
    echo "Invalid input. Pass one of the following:
-all dashboards                  to fetch all dashboards
-all monitors                    to fetch all monitors
-all metrics                     to fetch all active metric metadata
-monitor-ids id1, id2...         to fetch a list of monitors by id
-dashboard-ids id1, id2...       to fetch a list of dashboards by id
-metric-ids name1, name2...    to fetch a list of metric metadata by name
    "
    exit 1
esac
done