#!/usr/bin/env bash

set -e

pdb_db_name=puppetdb
pg_port=5432

pg_user=postgresql
psql_cmd=psql


function printerr {
  echo "$@" >&2
}

function usage {
  cat <<USAGE
Usage: puppetdb delete-reports [OPTIONS]
    --db-name NAME        the puppetdb database name (default: $pdb_db_name)
    --pg-user USER        the postgres system user (default: $pg_user)
    --pg-port PORT        the postgres port to connect (default: $pg_port)
    --psql    PATH        the path to the psql command (default: $psql_cmd)

    This cli command can conflict with command submission from running
    PuppetDBs. If that happens, you should stop your PuppetDBs and re-run
    this command to avoid the conflict.
USAGE
}

function misuse {
  usage >&2
  exit 2
}

while test $# -gt 0; do
  case "$1" in
    --db-name)
      shift
      test $# -gt 0 || misuse
      pdb_db_name="$1"
      shift
      ;;
    --pg-user)
      shift
      test $# -gt 0 || misuse
      pg_user="$1"
      shift
      ;;
    --pg-port)
      shift
      test $# -gt 0 || misuse
      pg_port="$1"
      shift
      ;;
    --psql)
      shift
      test $# -gt 0 || misuse
      psql_cmd="$1"
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
        misuse
  esac
done

tmp_dir="$(mktemp -d)"
tmp_dir="$(cd "$tmp_dir" && pwd)"
trap 'rm -rf "$tmp_dir"' EXIT

chown "$pg_user:$pg_user" "$tmp_dir"

# Verify that the PuppetDB schema version is the expected value
# so that we do not incorrectly delete the report data.
expected_schema_ver=88
su - -s /bin/sh "$pg_user" -c "$psql_cmd -p $pg_port -d $pdb_db_name -c 'COPY ( SELECT max(version) FROM schema_migrations ) TO STDOUT;' > $tmp_dir/schema_ver"
actual_schema_ver="$(cat "$tmp_dir/schema_ver")"
if test "$actual_schema_ver" -ne $expected_schema_ver; then
  printerr "Current schema version '${actual_schema_ver}' does not match the expected version '$expected_schema_ver'."
  exit 2
fi


cat > "$tmp_dir/delete_reports.sql" <<"DELETE"
BEGIN TRANSACTION;

DO $$ DECLARE
    r RECORD;
BEGIN
    FOR r IN (SELECT inhrelid::regclass AS child FROM pg_catalog.pg_inherits WHERE inhparent = 'reports_historical'::regclass OR inhparent = 'resource_events_historical'::regclass) LOOP
        EXECUTE 'DROP TABLE ' || quote_ident(r.child::text);
    END LOOP;

    EXECUTE 'TRUNCATE resource_events_latest';
    EXECUTE 'TRUNCATE reports_latest';
END $$;

COMMIT TRANSACTION;
DELETE

chown "$pg_user:$pg_user" "$tmp_dir/delete_reports.sql"

su - "$pg_user" "$psql_cmd -p $pg_port -d $pdb_db_name -f $tmp_dir/delete_reports.sql >&2"
