#!/usr/bin/env python3
"""Keep an extra COSMIC panel on the monitor you want, by position.

    cosmic-tools-panel-follow-output [--dry-run] [--no-restart] [--panel NAME]

A panel's `output` setting names a connector such as DP-5. Those names are not
stable: re-plugging a cable or a dock can renumber them, and a panel whose
output no longer exists silently never appears. This resolves the wanted
monitor by position (PANEL_OUTPUT_POSITION = leftmost | rightmost, or a fixed
connector name) and rewrites `output` only when it no longer matches, backing
up the old value first. cosmic-panel is restarted only when something changed,
and never with --no-restart.

Reads PANEL_NAME and PANEL_OUTPUT_POSITION from
~/.config/cosmic-tools/panel-bar.conf. install.sh can register it as a systemd
user service that runs once after login.
"""

import argparse
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
for cand in (os.environ.get("COSMIC_TOOLS_PANEL_SHARE", ""),
             os.path.join(HERE, ".."),
             os.path.expanduser("~/.local/share/cosmic-tools/panel-bar")):
    if cand and os.path.isfile(os.path.join(cand, "lib", "ctconfig.py")):
        sys.path.insert(0, os.path.join(cand, "lib"))
        break
import ctconfig     # noqa: E402
import cosmicpanel  # noqa: E402


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--panel", default=None)
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--no-restart", action="store_true")
    args = ap.parse_args()

    name = args.panel or ctconfig.get("PANEL_NAME", "WordBar")
    conf = os.path.join(cosmicpanel.panel_dir(name), "output")
    if not os.path.isdir(os.path.dirname(conf)):
        print("no COSMIC panel named %s; create it with cosmic-tools-add-panel" % name,
              file=sys.stderr)
        return 1

    target = cosmicpanel.resolve_output(ctconfig.get("PANEL_OUTPUT_POSITION", "leftmost"))
    if not target:
        print("no enabled outputs found", file=sys.stderr)
        return 1

    try:
        with open(conf, encoding="utf-8") as fh:
            current = fh.read().strip()
    except OSError:
        current = ""
    want = "Name(%s)" % cosmicpanel.ron_string(target)
    if current == want:
        print("%s already on %s" % (name, target))
        return 0
    if args.dry_run:
        print("would change %s output %s -> %s" % (name, current or "(unset)", want))
        return 0

    dest = cosmicpanel.backup("panel-output", [conf])
    cosmicpanel.write_atomic(conf, want)
    print("%s output %s -> %s (backup in %s)" % (name, current or "(unset)", want, dest))
    # A new output binding is only read when the panel starts.
    if not args.no_restart:
        cosmicpanel.restart_panel()
    return 0


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