#!/bin/sh
##
##  cockroach-psql.sh -- CockroachDB PostgreSQL CLI Wrapper
##

if [ ! -x @l_prefix@/bin/psql ]; then
    echo "ERROR: no psql(1) command available -- please install OpenPKG package \"postgresql\" first" 1>&2
    exit 1
fi

if [ $# -lt 2 ]; then
    echo "USAGE: cockroach-psql <username> <database> [...]" 1>&2
    exit 1
fi

username="$1"; shift
database="$1"; shift

if [ ! -f @l_prefix@/etc/cockroach/certs/client.$username.crt -o ! -f @l_prefix@/etc/cockroach/certs/client.$username.key ]; then
    echo "ERROR: no certificate/key pair found for user \"$username\"" 1>&2
    exit 1
fi

host="`grep '^host=' @l_prefix@/etc/cockroach/cockroach.conf | sed -e 's;^[^=]*=;;'`"
port="`grep '^port=' @l_prefix@/etc/cockroach/cockroach.conf | sed -e 's;^[^=]*=;;'`"

exec @l_prefix@/bin/psql \
    "host=$host port=$port user=$username dbname=$database sslmode=require \
    sslcert=@l_prefix@/etc/cockroach/certs/client.$username.crt \
    sslkey=@l_prefix@/etc/cockroach/certs/client.$username.key" \
    ${1+"$@"}

