#!/bin/bash

BACKUPDIR="${1}"
DB="${2}"
DB_NEW="${3}"

print_usage() {
  echo -e "Usage: ${0} backupdir database [new_database]"
  echo -e "\n    Single InfluxDB online database restore."
  echo -e "\nOptions:\n"
  echo "    backupdir"
  echo "        Backup directory"
  echo "    database"
  echo "        Database to restore from"
  echo "    new_database"
  echo "        Database to restore to (if different than from)"
}

if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
  print_usage
  exit 1
fi

echo "This will restore (online) InfluxDB database:"
echo "name:  ${DB}"
if [ "$#" -eq 3 ]; then
  echo "to:    ${DB_NEW}"
fi
echo "from:  ${BACKUPDIR}/data/${DB}"
echo

read -p "Are you sure? [y/N]" -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]
then
  echo
  
  if [ "$#" -eq 2 ]; then
    echo "restore database ${DB}..."
    /usr/bin/influxd restore -online -db "${DB}" "${BACKUPDIR}/data/${DB}"
  elif [ "$#" -eq 3 ]; then
    echo "restore database ${DB} to ${DB_NEW}..."
    /usr/bin/influxd restore -online -db "${DB}" -newdb "${DB_NEW}" "${BACKUPDIR}/data/${DB}"
  fi

  echo  
  echo "grant privileges manually ('GRANT priv ON db TO user'):"
  echo "user:db,priv"
  echo "------------"
  grep -E "^${DB}\b" "${BACKUPDIR}"/user/grants_*.csv | sed -e 's/.*user\/grants_//g' -e 's/\.csv//g'
else
  echo
  echo "aborted."
fi
