#!/bin/bash

if [[ $@ =~ "--help" ]] || [[ $@ =~ "-h" ]] || [ $# -ne 1 ]; then
	echo "Usage: `basename $0` -h | --help | output-file"
	exit
fi

if [ $(spacewalk-cfg-get db_backend) = "postgresql" ]; then
	sql="
select schemaname as schema,
       relname as table,
       n_live_tup as rows
  from pg_stat_user_tables
 order by n_live_tup desc;

select con.conname as name,
       con.contype as type,
       cl.relname as table,
       pg_get_expr(conbin, conrelid) as src
  from pg_constraint con,
       pg_class cl
 where cl.oid = con.conrelid
 order by name;

select
        rvi.label, to_char(rvi.created, 'YYYY-MM-DD') as created,
        to_char(rvi.modified, 'YYYY-MM-DD') as modified,
        rpn.name,
        rpe.epoch,
        rpe.version,
        rpe.release
from
        rhnVersionInfo rvi,
        rhnPackageName rpn,
        rhnPackageEvr rpe
where
        rvi.evr_id = rpe.id and
        rvi.name_id = rpn.id
order by created;
"

fi

output=$(echo "$sql" | spacewalk-sql --select-mode -)

if [ "$1" = "-" ]; then
        echo "$output"
else
        echo "$output" > $1
fi
