#!/usr/bin/env python3


import os
from subprocess import run

import click

PROJ_NAME = os.environ["PROJ_NAME"]


def show_pgpool():
    cmd = 'dx pgpool -- psql -P pager=off -U postgres -d postgres -c "show pool_nodes;"'
    print(f"\n=== {cmd} ===")
    run(cmd, shell=True)


def show_pg():
    for alive in ["pg1", "pg2"]:
        cmd = f"dx {alive} -- rep show"
        print(f"=== {cmd} === ")
        proc = run(cmd, capture_output=True, shell=True, text=True)
        if proc.returncode in [0, 25]:
            print(proc.stdout)


def show_services():
    print(f"=== docker stack services {PROJ_NAME} === ")
    run(f"docker stack services {PROJ_NAME}", shell=True)


def show_stack(verbose):
    print(f"\n=== docker stack ps {PROJ_NAME} === ")
    no_trunc = "--no-trunc" if verbose else ""
    run(
        f"docker stack ps {PROJ_NAME} {no_trunc} | GREP_COLOR='01;32' egrep --color=always '(^.*Running.*$)|$' | GREP_COLOR='01;31' egrep --color=always '(^.*Ready.*$)|$'",
        shell=True,
    )


@click.option("-v", "--verbose", is_flag=True)
@click.command()
def main(verbose):
    show_services()
    show_stack(verbose)
    show_pgpool()
    show_pg()


if __name__ == "__main__":
    main()
