#!/usr/bin/python3
# blob:summary=Show Syncthing folders and devices, start or stop it, rescan, and open the web UI
# blob:args=[status|start|stop|toggle|rescan [folder]|open]
# blob:group=network

from __future__ import annotations

import json
import os
import shutil
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ElementTree
from pathlib import Path
from typing import Any

SERVICE_NAME = "syncthing.service"
STATE_HOME = Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local" / "state")))
CONFIG_HOME = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")))
CONFIG_FILES = (STATE_HOME / "syncthing" / "config.xml", CONFIG_HOME / "syncthing" / "config.xml")
REQUEST_TIMEOUT = 2


def run(command: list[str]) -> bool:
  try:
    return subprocess.run(command, capture_output=True, timeout=15).returncode == 0
  except (OSError, subprocess.TimeoutExpired):
    return False


def service_active() -> bool:
  return run(["systemctl", "--user", "is-active", "--quiet", SERVICE_NAME])


def read_gui_settings() -> dict[str, str] | None:
  for config_file in CONFIG_FILES:
    try:
      gui = ElementTree.parse(config_file).getroot().find("gui")
    except (OSError, ElementTree.ParseError):
      continue
    if gui is None:
      continue
    address = (gui.findtext("address") or "127.0.0.1:8384").strip()
    host, _, port = address.rpartition(":")
    if host in ("", "0.0.0.0", "[::]"):
      host = "127.0.0.1"
    scheme = "https" if gui.get("tls") == "true" else "http"
    return {"url": f"{scheme}://{host}:{port}", "apiKey": (gui.findtext("apikey") or "").strip()}
  return None


class Api:
  def __init__(self, settings: dict[str, str]) -> None:
    self.base_url = settings["url"]
    self.api_key = settings["apiKey"]

  def call(self, path: str, method: str = "GET", query: dict[str, str] | None = None) -> Any:
    url = self.base_url + path
    if query:
      url += "?" + urllib.parse.urlencode(query)
    request = urllib.request.Request(url, method=method, headers={"X-API-Key": self.api_key})
    with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response:
      body = response.read()
    return json.loads(body) if body else None

  def reachable(self) -> bool:
    try:
      self.call("/rest/system/ping")
    except (OSError, urllib.error.URLError, ValueError):
      return False
    return True


def folder_info(api: Api, folder: dict[str, Any]) -> dict[str, Any]:
  info = {
    "id": folder["id"],
    "label": folder.get("label") or folder["id"],
    "paused": bool(folder.get("paused")),
    "state": "paused" if folder.get("paused") else "unknown",
    "percent": 100,
    "needBytes": 0,
    "needFiles": 0,
    "errors": 0,
  }
  if info["paused"]:
    return info
  try:
    status = api.call("/rest/db/status", query={"folder": folder["id"]})
  except (OSError, urllib.error.URLError, ValueError):
    return info
  global_bytes = status.get("globalBytes", 0)
  in_sync_bytes = status.get("inSyncBytes", 0)
  info["state"] = status.get("state") or "idle"
  info["percent"] = 100 if global_bytes <= 0 else int(in_sync_bytes * 100 / global_bytes)
  info["needBytes"] = status.get("needBytes", 0)
  info["needFiles"] = status.get("needFiles", 0)
  info["errors"] = status.get("pullErrors", 0) + status.get("errors", 0)
  info["globalBytes"] = global_bytes
  info["inSyncBytes"] = in_sync_bytes
  return info


def overall_state(folders: list[dict[str, Any]]) -> str:
  states = [folder["state"] for folder in folders]
  if any(folder["errors"] > 0 or folder["state"] == "error" for folder in folders):
    return "error"
  if any(state.startswith("sync") for state in states):
    return "syncing"
  if any(state.startswith("scan") for state in states):
    return "scanning"
  if folders and all(state == "paused" for state in states):
    return "paused"
  return "idle"


def status() -> dict[str, Any]:
  result: dict[str, Any] = {
    "installed": shutil.which("syncthing") is not None,
    "running": False,
    "service": service_active(),
    "url": "",
    "state": "stopped",
    "percent": 100,
    "needBytes": 0,
    "folders": [],
    "devices": [],
    "error": "",
  }
  settings = read_gui_settings()
  if settings is None:
    if result["installed"]:
      result["error"] = "Syncthing has not created its config yet"
    return result
  result["url"] = settings["url"]
  api = Api(settings)
  if not api.reachable():
    return result
  result["running"] = True
  try:
    my_id = api.call("/rest/system/status").get("myID", "")
    folders = api.call("/rest/config/folders")
    devices = api.call("/rest/config/devices")
    connections = api.call("/rest/system/connections").get("connections", {})
  except (OSError, urllib.error.URLError, ValueError) as error:
    result["error"] = f"Syncthing did not answer: {error}"
    return result
  result["folders"] = [folder_info(api, folder) for folder in folders]
  result["devices"] = [
    {
      "id": device["deviceID"],
      "name": device.get("name") or device["deviceID"][:7],
      "paused": bool(device.get("paused")),
      "connected": bool(connections.get(device["deviceID"], {}).get("connected")),
    }
    for device in devices
    if device["deviceID"] != my_id
  ]
  global_bytes = sum(folder.get("globalBytes", 0) for folder in result["folders"])
  in_sync_bytes = sum(folder.get("inSyncBytes", 0) for folder in result["folders"])
  result["percent"] = 100 if global_bytes <= 0 else int(in_sync_bytes * 100 / global_bytes)
  result["needBytes"] = sum(folder["needBytes"] for folder in result["folders"])
  result["state"] = overall_state(result["folders"])
  return result


def start() -> int:
  if not shutil.which("syncthing"):
    print("Syncthing is not installed", file=sys.stderr)
    return 1
  return 0 if run(["systemctl", "--user", "enable", "--now", SERVICE_NAME]) else 1


def stop() -> int:
  if service_active():
    return 0 if run(["systemctl", "--user", "disable", "--now", SERVICE_NAME]) else 1
  settings = read_gui_settings()
  if settings is None:
    return 0
  try:
    Api(settings).call("/rest/system/shutdown", method="POST")
  except (OSError, urllib.error.URLError, ValueError):
    pass
  run(["systemctl", "--user", "disable", SERVICE_NAME])
  return 0


def rescan(folder_id: str) -> int:
  settings = read_gui_settings()
  if settings is None:
    return 1
  try:
    Api(settings).call("/rest/db/scan", method="POST", query={"folder": folder_id} if folder_id else None)
  except (OSError, urllib.error.URLError, ValueError) as error:
    print(f"Rescan failed: {error}", file=sys.stderr)
    return 1
  return 0


def open_web_ui() -> int:
  settings = read_gui_settings()
  if settings is None:
    print("Syncthing has not created its config yet", file=sys.stderr)
    return 1
  subprocess.Popen(["xdg-open", settings["url"]], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
  return 0


def main() -> int:
  action = sys.argv[1] if len(sys.argv) > 1 else "status"
  if action == "status":
    print(json.dumps(status()))
    return 0
  if action == "start":
    return start()
  if action == "stop":
    return stop()
  if action == "toggle":
    settings = read_gui_settings()
    running = settings is not None and Api(settings).reachable()
    return stop() if running else start()
  if action == "rescan":
    return rescan(sys.argv[2] if len(sys.argv) > 2 else "")
  if action == "open":
    return open_web_ui()
  print("Usage: blob-syncthing [status|start|stop|toggle|rescan [folder]|open]", file=sys.stderr)
  return 2


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