#!/usr/bin/env python3.8
import socket
import subprocess as sub
from pathlib import Path

import click

CONNECTION_CONFIG = {
    "pg1": {
        "node_id": 1,
        "node_name": "pg1",
        "conninfo": "host=pg1 user=repmgr dbname=repmgr",
        "data_directory": "/var/lib/postgresql/12/main",
    },
    "pg2": {
        "node_id": 2,
        "node_name": "pg2",
        "conninfo": "host=pg2 user=repmgr dbname=repmgr",
        "data_directory": "/var/lib/postgresql/12/main",
    },
}


def to_config_file(conf):
    ret = [
        "# Auto generated by rep. This file is required for auto failover actions. Do not delete or modify!"
    ]
    for k, v in conf.items():
        if type(v) is str:
            ret.append(f"{k}='{v}'")
        elif type(v) is int:
            ret.append(f"{k}={v}")
    return "\n".join(ret)


def command_prefix():
    file = Path(f"/etc/repmgr/{socket.gethostname()}.conf")
    file.write_text(to_config_file(CONNECTION_CONFIG[socket.gethostname()]) + "\n")
    cmd = ["repmgr", "-f", file]
    return cmd


@click.group()
@click.pass_context
def main(ctx):
    pass


@main.command()
@click.argument("from_node", type=click.Choice(["pg1", "pg2"]))
@click.option("-f", "-F", "--force", is_flag=True)
def clonefrom(from_node, force):
    cmd = command_prefix()
    cmd += ["standby", "clone", "-d", CONNECTION_CONFIG[from_node]["conninfo"]]
    if force:
        cmd += ["--force"]
    sub.run(cmd)
    cmd = command_prefix()
    cmd += [
        "standby",
        "register",
        "-d",
        CONNECTION_CONFIG[from_node]["conninfo"],
        "--force",
    ]
    sub.run(cmd)


@main.command()
def show():
    cmd = command_prefix()
    cmd += ["cluster", "show"]
    sub.run(cmd)


@main.group()
def register():
    pass


@register.command(name="primary")
@click.option("-f", "-F", "--force", is_flag=True)
def register_primary(force):
    cmd = command_prefix()
    cmd += ["primary", "register"]
    if force:
        cmd += ["--force"]
    sub.run(cmd)


@register.command(name="standby")
@click.option("-f", "-F", "--force", is_flag=True)
def register_standby(force):
    cmd = command_prefix()
    cmd += ["standby", "register"]
    if force:
        cmd += ["--force"]
    sub.run(cmd)


@main.command()
def init():
    sub.run(["wait-for-it", "-t", "30", "localhost:5432"])
    sub.run(["createuser", "-s", "repmgr"])
    sub.run(["createdb", "repmgr", "-O", "repmgr"])


if __name__ == "__main__":
    main(obj={})
