#!/bin/bash

set -o pipefail

unset host port db

argv=`getopt -o 'h:p:d:' -l 'host:,port:,database:' -- "$@"` || exit $?
eval "set -- $argv"
while [[ $1 != -- ]]; do
  case $1 in
    -h|--host)     host=$2;     shift 2;;
    -p|--port)     port=$2;     shift 2;;
    -d|--database) db=$2; shift 2;;
  esac
done
shift

for file in "$@"; do
  table=${file%.csv}
  if [[ $table = $f ]]; then
    echo "Unexpected file name: $file, expected *.csv" >&2
    exit 1
  fi

  echo "delete from $table;"
  echo "\\copy $table from '$file';"
done | psql ${host+-h "$host"} ${port+-p "$port"} ${db+-d "$db"}
