#!/usr/bin/env python3
"""Read-only PostgreSQL probe through an already configured QGTunnel listener."""
import os
import sys


def main():
    try:
        import psycopg
        with psycopg.connect(
            host=os.environ['PGHOST'],  # Real certificate hostname.
            hostaddr='127.0.0.1',        # Local tunnel listener.
            port=int(os.environ.get('QG_DB_LOCAL_PORT', '15432')),
            dbname=os.environ['PGDATABASE'], user=os.environ['PGUSER'],
            password=os.environ['PGPASSWORD'], sslmode='verify-full',
            sslrootcert=os.environ['PGSSLROOTCERT'], connect_timeout=10,
            options='-c default_transaction_read_only=on -c statement_timeout=15000'
        ) as conn:
            with conn.cursor() as cur:
                cur.execute('SELECT 1')
                if cur.fetchone() != (1,):
                    raise RuntimeError()
        print('PASS: read-only database probe completed')
    except Exception:
        print('Database probe failed; check listener, TLS, and authorization.', file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    sys.exit(main())
