"""
nginx deploy
"""
import subprocess
from pyinfra.operations import files, apt


def get_pass(filename: str) -> str:
    """Get the data from the password manager."""
    try:
        r = subprocess.run(["pass", "show", filename], capture_output=True)
    except FileNotFoundError:
        readme_url = "https://git.0x90.space/deltachat/secrets"
        print(f"Please install pass and pull the latest version of our pass secrets from {readme_url}")
        exit()
    return r.stdout.decode('utf-8')


def deploy_tmux(home_dir="/root", escape_key="C-b", additional_config=[]):
    apt.packages(
        name="apt install tmux",
        packages=["tmux"],
    )

    config = [
        f"set-option -g prefix {escape_key}",
        "set-option -g aggressive-resize on",
        "set-option -g mouse on",
        "set-option -g set-titles on",
        "set-option -g set-titles-string '#I:#W - \"#H\"'",
        "unbind-key C-b",
        "bind-key ` send-prefix",
        "bind-key a last-window",
        "bind-key k kill-session",
    ]
    for item in additional_config:
        config.append(item)
    for line in config:
        files.line(
            path=f"{home_dir}/.tmux.conf",
            line=line,
        )

    dot_profile_add = """
# autostart tmux
if [ -t 0 -a -z "$TMUX" ]
then
  test -z "$(tmux list-sessions)" && exec tmux new -s "$USER" || exec tmux new -A -s $(tty | tail -c +6) -t "$USER"
fi
"""
    files.block(
        name="connect to tmux session on login",
        path=f"{home_dir}/.profile",
        content=dot_profile_add,
        try_prevent_shell_expansion=True,
    )