#!/bin/sh

check_tool() {
  if ! command -v "$1" >/dev/null; then
    echo "Required tool \`$2\` are not installed or binary \`$1\` not found." >&2
    exit 1
  fi
}

BIN_PG_DUMP=${BIN_PG_DUMP:-pg_dump}
BIN_PSQL=${BIN_PSQL:-psql}
BIN_GIT=${BIN_GIT:-git}

check_tool $BIN_PG_DUMP "pg_dump"
check_tool $BIN_PSQL "psql"
check_tool $BIN_GIT "git"

# Logging functions
log_info()    { text=$1; shift; printf "%b%s ${text}%b\n" "$BLUE"   "$INFO_EM" "$@" "$NC"; }
log_success() { text=$1; shift; printf "%b%s ${text}%b\n" "$GREEN"  "$SUCC_EM" "$@" "$NC"; }
log_warning() { text=$1; shift; printf "%b%s ${text}%b\n" "$YELLOW" "$WARN_EM" "$@" "$NC"; }
log_error()   { text=$1; shift; printf "%b%s ${text}%b\n" "$RED"    "$ERRO_EM" "$@" "$NC"; }
log_step()    { text=$1; shift; printf "%b%s ${text}%b\n" "$PURPLE" "$STEP_EM" "$@" "$NC"; }

log_header() { printf "\n%b=== %s ===%b\n" "$WHITE" "$@" "$NC"; }

log_step "Detecting local directories..."
if git_root=$($BIN_GIT rev-parse --show-toplevel 2>/dev/null); then
  LOCAL_DIR="$git_root"
  log_success "Found git root: ${WHITE}$LOCAL_DIR${NC}"
else
  LOCAL_DIR="$(pwd)"
  log_warning "Not in git repo, using current dir: ${WHITE}$LOCAL_DIR${NC}"
  read -p "Are you realy want continue? (y/n): " CONTINUE
  if [ "$CONTINUE" != "y" ]; then
    log_error "Aborting..."
    exit 0
  fi
fi

SCHEMA_DIR="$LOCAL_DIR/db/schema"

read -p "This will remove all schema files in $SCHEMA_DIR. Are you sure? (y/n): " CONTINUE
if [ "$CONTINUE" != "y" ]; then
  log_error "Aborting..."
  exit 0
fi

log_step "Removing old schema files from $SCHEMA_DIR..."
rm -rf "$SCHEMA_DIR"

mkdir -p "$SCHEMA_DIR"

# TODO(yukkop): check postgres connection
# TODO(yukkop): check if connection url provided
# TODO(yukkop): check if connection url is valid

log_step "Dumping schemas..."
for schema in $("$BIN_PSQL" "$1" -t -c "
  SELECT n.nspname
  FROM pg_namespace n
  WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast', 'pg_temp_1', 'pg_toast_temp_1')
    AND n.nspname NOT LIKE 'pg_%temp%';
"); do
  log_step "Dumping schema: ${WHITE}$schema${NC}"
  echo '\q' > "$SCHEMA_DIR/${schema}.sql"
  if ! "$BIN_PG_DUMP" --schema-only --schema="$schema" "$1" >> "$SCHEMA_DIR/${schema}.sql"; then
    log_error "Failed to dump schema: ${WHITE}$schema${NC}"
    exit 1
  fi
done

log_success "Done"
