#!/bin/bash

set -e


BIN_NAME=$(basename "$0")

function stdout() {
  echo -e "[$BIN_NAME] $1"
}

function stderr() {
  echo -e "[$BIN_NAME] $1" 1>&2
}

function usage() {
  stderr "usage:"
  stderr "\t# $BIN_NAME create"
  stderr "\t# $BIN_NAME restore"
}

if [[ $EUID -ne 0 ]]; then
  stderr "fail: this script must be run as root"
  exit 1
fi

if [ -z "$1" ]; then
  stderr "fail: invalid args"
  usage "$0"
  exit 1
fi

function handle_create() {
  local sql_path=$1

  cat << SQL > "$sql_path"
  truncate table core.opt;
  truncate table public.valuestore;
  truncate table public.collection_event_origin;
  truncate table public.collection_event_lane;
  truncate table public.collection_event_profile;
SQL

  pg_dump -p 5433 -U autocode --column-inserts --data-only \
    --table=core.opt                                       \
    --table=public.valuestore                              \
    --table=public.collection_event_origin                 \
    --table=public.collection_event_lane                   \
    --table=public.collection_event_profile                \
    autocode >> "$sql_path"
}

function handle_restore() {
  local sql_path=$1
  psql -p 5433 autocode autocode < "$sql_path"
}

case $1 in
  create)
    stdout "exec: create"
    handle_create ./db.sql
    stdout "done: create"
    ;;

  restore)
    stdout "exec: restore"
    handle_restore ./db.sql
    stdout "done: restore"
    ;;

  *)
    stderr "fail: unsupported (action:$1)"
    usage "$0"
    exit 1
    ;;
esac
