#!/bin/bash
# POPFTP installer for Raspberry Pi OS (desktop version)
# Installs the dashboard window, its background service and admin mode.
set -e
DESKUSER="${SUDO_USER:-$USER}"
DESKHOME=$(getent passwd "$DESKUSER" | cut -d: -f6)

echo "=== POPFTP setup ==="
if [ "$(systemctl get-default)" != "graphical.target" ]; then
  echo "This Pi is not running the desktop version of Raspberry Pi OS."
  echo "The dashboard needs it. See part 1 of the manual."
  exit 1
fi

if [ -f /etc/ftpdash/admin.json ]; then
  echo "An admin password is already set; keeping it."
  ADMINPW=""
else
  echo "Choose an admin password for the dashboard's Admin button."
  read -s -p "Admin password: " ADMINPW; echo
  read -s -p "Type it again: " ADMINPW2; echo
  if [ "$ADMINPW" != "$ADMINPW2" ] || [ ${#ADMINPW} -lt 4 ]; then
    echo "Passwords don't match or are shorter than 4 characters. Run the installer again."
    exit 1
  fi
fi

echo "--- Installing Python libraries and firewall tool ---"
sudo apt update
sudo apt install -y python3-pyqt5 python3-psutil nftables fonts-inter || sudo apt install -y python3-pyqt5 python3-psutil nftables

echo "--- Installing the dashboard files ---"
sudo mkdir -p /opt/ftpdash /etc/ftpdash
sudo tee /opt/ftpdash/collector.py >/dev/null <<'PYEOF'
#!/usr/bin/env python3
"""FTP dashboard collector.

Runs as root (systemd service). Every 2 seconds it gathers FTP and system
figures and writes them to /run/ftpdash/status.json for the dashboard window.
"""
import json
import os
import re
import shutil
import socket
import subprocess
import time
from collections import deque
from datetime import datetime, date

import psutil

LOG = "/var/log/vsftpd.log"
OUT_DIR = "/run/ftpdash"
OUT = os.path.join(OUT_DIR, "status.json")
NAMES_FILE = "/etc/ftpdash/names.json"
BLOCKED_FILE = "/etc/ftpdash/blocked.json"
VSFTPD_CONF = "/etc/vsftpd.conf"
USERLIST = "/etc/vsftpd.userlist"
RESET_FLAG = "/run/ftpdash/reset-totals"
SINCE_FILE = "/run/ftpdash/totals-since"
USB_MOUNT = "/home/c64/usb"
FTP_PORT = 21
PASV_MIN, PASV_MAX = 40000, 40100
INTERVAL = 2.0
HISTORY_STEP = 10      # seconds per history point
HISTORY_POINTS = 360   # 60 minutes

LINE = re.compile(
    r'^(?P<ts>\w{3} \w{3}\s+\d+ \d\d:\d\d:\d\d \d{4}) \[pid \d+\] '
    r'(?:\[(?P<user>[^\]]+)\] )?'
    r'(?:(?P<res>OK|FAIL) )?(?P<act>[A-Z]+(?: [A-Z]+)?): '
    r'Client "(?P<ip>[^"]+)"'
    r'(?:, "(?P<path>[^"]*)")?'
    r'(?:, (?P<bytes>\d+) bytes)?'
    r'(?:, (?P<rate>[\d.]+)Kbyte/sec)?'
)


def clean_ip(ip):
    return ip[7:] if ip.startswith("::ffff:") else ip


def read_only():
    try:
        with open(VSFTPD_CONF) as f:
            for line in f:
                if line.strip().startswith("write_enable="):
                    return line.strip().split("=", 1)[1].upper() != "YES"
    except Exception:
        pass
    return False


def ftp_accounts():
    try:
        with open(USERLIST) as f:
            return [u.strip() for u in f if u.strip() and not u.startswith("#")]
    except Exception:
        return []


def blocked():
    try:
        with open(BLOCKED_FILE) as f:
            return list(json.load(f))
    except Exception:
        return []


def load_names():
    try:
        with open(NAMES_FILE) as f:
            return {k: str(v) for k, v in json.load(f).items()}
    except Exception:
        return {}


class LogReader:
    """Follows the vsftpd log, keeps today's totals and recent events."""

    def __init__(self):
        self.inode = None
        self.offset = 0
        self.day = date.today()
        self.recent = deque(maxlen=40)
        self.last_user = {}       # ip -> user
        self.connected_at = {}    # ip -> epoch of last CONNECT
        try:
            with open(SINCE_FILE) as f:
                self.since = float(f.read().strip())
        except Exception:
            self.since = 0.0
        self.reset_totals()

    def reset_totals(self):
        self.totals = {"downloads": 0, "uploads": 0, "bytes_down": 0, "bytes_up": 0,
                       "logins": 0, "failed_logins": 0, "deletes": 0}
        self.hourly = {"downloads": [0] * 24, "uploads": [0] * 24,
                       "bytes_down": [0] * 24, "bytes_up": [0] * 24}

    def poll(self):
        if os.path.exists(RESET_FLAG):
            try:
                os.remove(RESET_FLAG)
            except OSError:
                pass
            self.reset_totals()
            self.recent.clear()
            self.since = time.time()
            try:
                with open(SINCE_FILE, "w") as f:
                    f.write(str(self.since))
            except OSError:
                pass
        if date.today() != self.day:
            self.day = date.today()
            self.reset_totals()
        try:
            st = os.stat(LOG)
        except FileNotFoundError:
            return
        if st.st_ino != self.inode or st.st_size < self.offset:
            self.inode, self.offset = st.st_ino, 0  # new or rotated log
        if st.st_size == self.offset:
            return
        with open(LOG, "r", errors="replace") as f:
            f.seek(self.offset)
            for line in f:
                self.handle(line.rstrip("\n"))
            self.offset = f.tell()

    def handle(self, line):
        m = LINE.match(line)
        if not m:
            return
        try:
            ts = datetime.strptime(" ".join(m.group("ts").split()), "%a %b %d %H:%M:%S %Y")
        except ValueError:
            return
        ip = clean_ip(m.group("ip"))
        act, res, user = m.group("act"), m.group("res"), m.group("user")
        if act == "CONNECT":
            self.connected_at[ip] = ts.timestamp()
            return
        if act == "LOGIN" and res == "OK" and user:
            self.last_user[ip] = user
        if ts.timestamp() < self.since:
            return  # before the last "reset totals"
        today = ts.date() == date.today()
        size = int(m.group("bytes") or 0)
        if today:
            if act == "LOGIN":
                self.totals["logins" if res == "OK" else "failed_logins"] += 1
            elif act == "DOWNLOAD" and res == "OK":
                self.totals["downloads"] += 1
                self.totals["bytes_down"] += size
                self.hourly["downloads"][ts.hour] += 1
                self.hourly["bytes_down"][ts.hour] += size
            elif act == "UPLOAD" and res == "OK":
                self.totals["uploads"] += 1
                self.totals["bytes_up"] += size
                self.hourly["uploads"][ts.hour] += 1
                self.hourly["bytes_up"][ts.hour] += size
            elif act in ("DELETE", "RMDIR") and res == "OK":
                self.totals["deletes"] += 1
        self.recent.appendleft({
            "time": ts.strftime("%H:%M:%S") if today else ts.strftime("%b %d %H:%M"),
            "result": res or "",
            "action": act,
            "user": user or self.last_user.get(ip, ""),
            "ip": ip,
            "path": m.group("path") or "",
            "bytes": size,
            "rate_kbs": float(m.group("rate") or 0),
        })


def service_active(name):
    try:
        return subprocess.run(["systemctl", "is-active", name], capture_output=True,
                              text=True, timeout=3).stdout.strip() == "active"
    except Exception:
        return False


def local_ip():
    try:
        out = subprocess.run(["hostname", "-I"], capture_output=True, text=True, timeout=3).stdout.split()
        return out[0] if out else ""
    except Exception:
        return ""


def connections(reader, names):
    sessions, transfers = {}, {}
    try:
        conns = psutil.net_connections(kind="inet")
    except Exception:
        conns = []
    for c in conns:
        if c.status != psutil.CONN_ESTABLISHED or not c.raddr or not c.laddr:
            continue
        ip = clean_ip(c.raddr.ip)
        if c.laddr.port == FTP_PORT:
            sessions[ip] = sessions.get(ip, 0) + 1
        elif PASV_MIN <= c.laddr.port <= PASV_MAX:
            transfers[ip] = transfers.get(ip, 0) + 1
    rows = []
    now = time.time()
    for ip, n in sorted(sessions.items()):
        since = reader.connected_at.get(ip)
        rows.append({
            "ip": ip,
            "name": names.get(ip, ""),
            "user": reader.last_user.get(ip, ""),
            "sessions": n,
            "transferring": transfers.get(ip, 0) > 0,
            "connected_secs": int(now - since) if since else None,
        })
    return rows


def storage():
    disks = []
    for label, path in (("SD card", "/"), ("USB drive", USB_MOUNT)):
        if path != "/" and not os.path.ismount(path):
            continue
        try:
            u = shutil.disk_usage(path)
            disks.append({"label": label, "path": path, "total": u.total, "used": u.used, "free": u.free})
        except OSError:
            pass
    return disks


def cpu_temp():
    try:
        with open("/sys/class/thermal/thermal_zone0/temp") as f:
            return round(int(f.read().strip()) / 1000, 1)
    except Exception:
        return None


def load_history():
    """Keep the trend history across a collector restart (not across a reboot)."""
    try:
        with open(OUT) as f:
            old = json.load(f).get("history", [])
        if old and time.time() - old[-1]["t"] < 15 * 60:
            return deque(old, maxlen=HISTORY_POINTS)
    except Exception:
        pass
    return deque(maxlen=HISTORY_POINTS)


def main():
    os.makedirs(OUT_DIR, exist_ok=True)
    reader = LogReader()
    history = load_history()
    acc = {"rx": 0.0, "tx": 0.0, "cpu": 0.0, "mem": 0.0, "temp": 0.0, "sessions": 0, "n": 0}
    last_push = time.time()
    last_net = psutil.net_io_counters()
    last_t = time.time()
    psutil.cpu_percent(None)
    host = socket.gethostname()
    while True:
        reader.poll()
        names = load_names()
        now = time.time()
        net = psutil.net_io_counters()
        dt = max(now - last_t, 0.001)
        rx = (net.bytes_recv - last_net.bytes_recv) / dt
        tx = (net.bytes_sent - last_net.bytes_sent) / dt
        last_net, last_t = net, now
        mem = psutil.virtual_memory()
        cpu = psutil.cpu_percent(None)
        temp = cpu_temp()
        conns = connections(reader, names)
        acc["rx"] += rx; acc["tx"] += tx; acc["cpu"] += cpu; acc["mem"] += mem.percent
        acc["temp"] += temp or 0; acc["sessions"] = max(acc["sessions"], len(conns)); acc["n"] += 1
        if now - last_push >= HISTORY_STEP and acc["n"]:
            n = acc["n"]
            history.append({"t": int(now), "rx": acc["rx"] / n, "tx": acc["tx"] / n, "cpu": acc["cpu"] / n,
                            "mem": acc["mem"] / n, "temp": acc["temp"] / n if temp is not None else None,
                            "sessions": acc["sessions"]})
            acc = {"rx": 0.0, "tx": 0.0, "cpu": 0.0, "mem": 0.0, "temp": 0.0, "sessions": 0, "n": 0}
            last_push = now
        status = {
            "updated": int(now),
            "host": host,
            "ip": local_ip(),
            "ftp_running": service_active("vsftpd"),
            "read_only": read_only(),
            "accounts": ftp_accounts(),
            "blocked": blocked(),
            "names": names,
            "ftp_port": FTP_PORT,
            "uptime_secs": int(now - psutil.boot_time()),
            "connections": conns,
            "totals": reader.totals,
            "hourly": reader.hourly,
            "history": list(history),
            "recent": list(reader.recent)[:25],
            "storage": storage(),
            "system": {
                "cpu_percent": cpu,
                "mem_percent": mem.percent,
                "mem_used": mem.used,
                "mem_total": mem.total,
                "temp_c": temp,
                "load": os.getloadavg(),
                "net_rx_bps": rx,
                "net_tx_bps": tx,
            },
        }
        tmp = OUT + ".tmp"
        with open(tmp, "w") as f:
            json.dump(status, f)
        os.chmod(tmp, 0o644)
        os.replace(tmp, OUT)
        time.sleep(INTERVAL)


if __name__ == "__main__":
    main()
PYEOF
sudo tee /opt/ftpdash/dashboard.py >/dev/null <<'PYEOF'
#!/usr/bin/env python3
"""POPFTP: desktop dashboard for the Raspberry Pi FTP server.

Reads /run/ftpdash/status.json (written by the ftpdash-collector service)
and refreshes every 2 seconds. A normal window: maximize, minimize or close it.
"""
import hashlib
import hmac
import json
import os
import subprocess
import sys
import time

from PyQt5.QtCore import Qt, QTimer, QRectF, QPointF
from PyQt5.QtGui import QColor, QPainter, QPen, QBrush, QFont, QLinearGradient, QPainterPath
from PyQt5.QtWidgets import (
    QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QGridLayout, QFrame,
    QTableWidget, QTableWidgetItem, QHeaderView, QSizePolicy, QAbstractItemView,
    QPushButton, QDialog, QTabWidget, QLineEdit, QComboBox, QCheckBox, QListWidget,
    QPlainTextEdit, QMessageBox, QInputDialog, QFormLayout, QGraphicsDropShadowEffect,
)

STATUS = os.environ.get("FTPDASH_STATUS", "/run/ftpdash/status.json")
ADMIN_FILE = os.environ.get("FTPDASH_ADMIN", "/etc/ftpdash/admin.json")
HELPER = ["sudo", "-n", "/usr/bin/python3", "/opt/ftpdash/admin_helper.py"]
ADMIN_TIMEOUT_MS = 15 * 60 * 1000
REFRESH_MS = 2000

# ---- light palette ----
BG = "#eef2f7"
PANEL = "#ffffff"
LINE = "#e3e8ef"
TEXT = "#0f172a"
MUTED = "#64748b"
ACCENT = "#2563eb"     # blue: primary, downloads, network in
ACCENT2 = "#f97316"    # orange: uploads, network out
OK = "#0891b2"         # cyan: running / healthy
WARN = "#f59e0b"
BAD = "#dc2626"
TRACK = "#e8edf4"

FONT = "'Inter', 'Piboto', 'Roboto', 'DejaVu Sans', sans-serif"

STYLE = f"""
QWidget {{ background: {BG}; color: {TEXT}; font-family: {FONT}; font-size: 14px; }}
QFrame#panel {{ background: {PANEL}; border: 1px solid {LINE}; border-radius: 16px; }}
QLabel {{ background: transparent; }}
QLabel#panelTitle {{ color: {TEXT}; font-size: 15px; font-weight: 700; }}
QLabel#panelSub {{ color: {MUTED}; font-size: 12px; }}
QLabel#kpiValue {{ font-size: 32px; font-weight: 800; letter-spacing: -0.5px; }}
QLabel#kpiLabel {{ color: {MUTED}; font-size: 13px; font-weight: 600; }}
QLabel#kpiDetail {{ color: {MUTED}; font-size: 12px; }}
QLabel#title {{ font-size: 22px; font-weight: 800; }}
QLabel#sub {{ color: {MUTED}; font-size: 13px; }}
QLabel#clock {{ font-size: 24px; font-weight: 700; }}
QTableWidget {{ background: transparent; border: none; font-size: 13px; }}
QTableWidget::item {{ padding: 4px 8px; border-bottom: 1px solid #eef2f6; }}
QTableWidget::item:selected {{ background: #dbeafe; color: {TEXT}; }}
QHeaderView::section {{ background: {PANEL}; color: {MUTED}; border: none; border-bottom: 1px solid {LINE};
                        padding: 6px 8px; font-weight: 600; font-size: 12px; }}
QPushButton {{ background: {PANEL}; color: {TEXT}; border: 1px solid #cbd5e1; border-radius: 9px; padding: 7px 16px; font-weight: 600; }}
QPushButton:hover {{ background: #f1f5f9; }}
QPushButton:disabled {{ color: #94a3b8; }}
QPushButton#primary {{ background: {ACCENT}; border-color: {ACCENT}; color: white; }}
QPushButton#primary:hover {{ background: #1d4ed8; }}
QPushButton#danger {{ background: #fef2f2; border-color: #fca5a5; color: #b91c1c; }}
QPushButton#danger:hover {{ background: #fee2e2; }}
QLineEdit, QComboBox, QPlainTextEdit, QListWidget {{ background: {PANEL}; border: 1px solid #cbd5e1; border-radius: 9px; padding: 6px 8px; selection-background-color: #bfdbfe; selection-color: {TEXT}; }}
QLineEdit:focus, QComboBox:focus {{ border-color: {ACCENT}; }}
QPlainTextEdit {{ font-family: 'DejaVu Sans Mono', monospace; font-size: 12px; }}
QTabWidget::pane {{ border: 1px solid {LINE}; border-radius: 12px; top: -1px; background: {PANEL}; }}
QTabBar::tab {{ background: transparent; color: {MUTED}; padding: 9px 18px; border: none; font-weight: 600; }}
QTabBar::tab:selected {{ color: {TEXT}; border-bottom: 2px solid {ACCENT}; }}
QCheckBox {{ spacing: 10px; background: transparent; }}
QCheckBox::indicator {{ width: 18px; height: 18px; border: 1.5px solid #94a3b8; border-radius: 5px; background: {PANEL}; }}
QCheckBox::indicator:checked {{ background: {ACCENT}; border-color: {ACCENT}; }}
"""


# ---------- formatting ----------

def human_bytes(n):
    n = float(n or 0)
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024 or unit == "TB":
            return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
        n /= 1024


def human_rate(bps):
    return human_bytes(bps) + "/s"


def human_secs(s):
    if s is None:
        return "–"
    d, s = divmod(int(s), 86400)
    h, s = divmod(s, 3600)
    m, s = divmod(s, 60)
    if d:
        return f"{d}d {h}h {m}m"
    if h:
        return f"{h}h {m}m"
    return f"{m}m {s}s"


def nice_max(v):
    """Round a maximum up to a tidy axis value."""
    if v <= 0:
        return 1.0
    mag = 10 ** len(str(int(v))) / 10 if v >= 1 else 1
    for step in (1, 2, 2.5, 5, 10):
        if v <= step * mag:
            return step * mag
    return 10 * mag


def qc(hex_color, alpha=255):
    c = QColor(hex_color)
    c.setAlpha(alpha)
    return c


# ---------- building blocks ----------

def shadow(w):
    eff = QGraphicsDropShadowEffect()
    eff.setBlurRadius(24)
    eff.setOffset(0, 4)
    eff.setColor(QColor(15, 23, 42, 22))
    w.setGraphicsEffect(eff)


def panel(title, sub=""):
    frame = QFrame()
    frame.setObjectName("panel")
    shadow(frame)
    lay = QVBoxLayout(frame)
    lay.setContentsMargins(18, 14, 18, 14)
    lay.setSpacing(8)
    head = QHBoxLayout()
    t = QLabel(title)
    t.setObjectName("panelTitle")
    head.addWidget(t)
    head.addStretch(1)
    s = QLabel(sub)
    s.setObjectName("panelSub")
    head.addWidget(s)
    lay.addLayout(head)
    frame.sub_label = s
    return frame, lay


def make_table(headers, stretch_col):
    t = QTableWidget(0, len(headers))
    t.setHorizontalHeaderLabels(headers)
    t.verticalHeader().setVisible(False)
    t.setShowGrid(False)
    t.setEditTriggers(QAbstractItemView.NoEditTriggers)
    t.setSelectionMode(QAbstractItemView.NoSelection)
    t.setFocusPolicy(Qt.NoFocus)
    h = t.horizontalHeader()
    for i in range(len(headers)):
        h.setSectionResizeMode(i, QHeaderView.Stretch if i == stretch_col else QHeaderView.ResizeToContents)
    h.setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
    t.verticalHeader().setDefaultSectionSize(30)
    return t


def cell(text, color=None):
    it = QTableWidgetItem(str(text))
    if color:
        it.setForeground(QColor(color))
    return it


class Sparkline(QWidget):
    def __init__(self, color=ACCENT):
        super().__init__()
        self.color = color
        self.values = []
        self.setFixedSize(130, 46)

    def set_values(self, values):
        self.values = [float(v or 0) for v in values]
        self.update()

    def paintEvent(self, _):
        v = self.values
        if len(v) < 2 or max(v) <= 0:
            return
        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)
        w, h = self.width(), self.height() - 4
        top = max(v)
        pts = [QPointF(i * w / (len(v) - 1), 2 + h - (x / top) * h) for i, x in enumerate(v)]
        path = QPainterPath(pts[0])
        for pt in pts[1:]:
            path.lineTo(pt)
        fill = QPainterPath(path)
        fill.lineTo(w, h + 2)
        fill.lineTo(0, h + 2)
        fill.closeSubpath()
        g = QLinearGradient(0, 0, 0, h)
        g.setColorAt(0, qc(self.color, 70))
        g.setColorAt(1, qc(self.color, 0))
        p.fillPath(fill, QBrush(g))
        p.setPen(QPen(QColor(self.color), 2))
        p.drawPath(path)
        p.end()


class Kpi(QFrame):
    def __init__(self, label, color=ACCENT):
        super().__init__()
        self.setObjectName("panel")
        shadow(self)
        lay = QHBoxLayout(self)
        lay.setContentsMargins(18, 14, 14, 14)
        col = QVBoxLayout()
        col.setSpacing(1)
        self.label = QLabel(label)
        self.label.setObjectName("kpiLabel")
        self.value = QLabel("–")
        self.value.setObjectName("kpiValue")
        self.detail = QLabel("")
        self.detail.setObjectName("kpiDetail")
        col.addWidget(self.label)
        col.addWidget(self.value)
        col.addWidget(self.detail)
        lay.addLayout(col, 1)
        self.spark = Sparkline(color)
        lay.addWidget(self.spark, 0, Qt.AlignBottom)

    def set(self, value, detail="", spark=None, detail_color=MUTED):
        self.value.setText(value)
        self.detail.setText(detail)
        self.detail.setStyleSheet(f"color: {detail_color};")
        if spark is not None:
            self.spark.set_values(spark)


class Gauge(QWidget):
    """270-degree dial with a value in the middle."""

    def __init__(self, title):
        super().__init__()
        self.title = title
        self.pct = 0.0
        self.text = "–"
        self.sub = ""
        self.color = ACCENT
        self.setMinimumSize(150, 150)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    def set(self, pct, text, sub="", warn=75, bad=90):
        self.pct = max(0.0, min(100.0, float(pct or 0)))
        self.text, self.sub = text, sub
        self.color = BAD if self.pct >= bad else WARN if self.pct >= warn else ACCENT
        self.update()

    def paintEvent(self, _):
        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)
        w, h = self.width(), self.height()
        title_h = 22
        size = min(w, h - title_h) - 8
        thick = max(10, size * 0.085)
        r = QRectF((w - size) / 2 + thick / 2, 4 + thick / 2, size - thick, size - thick)
        pen = QPen(QColor(TRACK), thick, Qt.SolidLine, Qt.RoundCap)
        p.setPen(pen)
        p.drawArc(r, 225 * 16, -270 * 16)
        if self.pct > 0:
            g = QLinearGradient(r.topLeft(), r.bottomRight())
            g.setColorAt(0, qc(self.color, 170))
            g.setColorAt(1, QColor(self.color))
            pen = QPen(QBrush(g), thick, Qt.SolidLine, Qt.RoundCap)
            p.setPen(pen)
            p.drawArc(r, 225 * 16, int(-270 * 16 * self.pct / 100))
        # value
        f = QFont(self.font())
        f.setPixelSize(int(size * 0.2))
        f.setWeight(QFont.Black)
        p.setFont(f)
        p.setPen(QColor(TEXT))
        p.drawText(r.adjusted(0, -size * 0.06, 0, -size * 0.06), Qt.AlignCenter, self.text)
        f2 = QFont(self.font())
        f2.setPixelSize(max(11, int(size * 0.075)))
        p.setFont(f2)
        p.setPen(QColor(MUTED))
        p.drawText(r.adjusted(0, size * 0.2, 0, size * 0.2), Qt.AlignCenter, self.sub)
        # title
        f3 = QFont(self.font())
        f3.setPixelSize(14)
        f3.setWeight(QFont.DemiBold)
        p.setFont(f3)
        p.setPen(QColor(TEXT))
        p.drawText(QRectF(0, h - title_h, w, title_h), Qt.AlignHCenter | Qt.AlignVCenter, self.title)
        p.end()


class LineChart(QWidget):
    """Area chart with gridlines, axis labels and a legend."""

    def __init__(self, fmt=human_rate):
        super().__init__()
        self.series = []      # (name, color, values)
        self.span_label = ""
        self.fmt = fmt
        self.setMinimumHeight(180)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    def set_series(self, series, span_label=""):
        self.series = series
        self.span_label = span_label
        self.update()

    def paintEvent(self, _):
        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)
        w, h = self.width(), self.height()
        left, right, top, bottom = 74, 10, 30, 24
        cw, ch = w - left - right, h - top - bottom
        small = QFont(self.font())
        small.setPixelSize(11)
        p.setFont(small)
        vals = [v for _, _, s in self.series for v in s]
        top_v = nice_max(max(vals) if vals else 0)
        # grid + y labels
        for i in range(5):
            y = top + ch * i / 4
            p.setPen(QPen(QColor("#edf1f6"), 1))
            p.drawLine(QPointF(left, y), QPointF(w - right, y))
            p.setPen(QColor(MUTED))
            p.drawText(QRectF(0, y - 8, left - 10, 16), Qt.AlignRight | Qt.AlignVCenter, self.fmt(top_v * (4 - i) / 4))
        # x labels
        p.drawText(QRectF(left, h - bottom + 4, 140, 16), Qt.AlignLeft, self.span_label)
        p.drawText(QRectF(w - right - 60, h - bottom + 4, 60, 16), Qt.AlignRight, "now")
        # legend
        lx = left
        f = QFont(self.font())
        f.setPixelSize(12)
        f.setWeight(QFont.DemiBold)
        p.setFont(f)
        for name, color, s in self.series:
            p.setPen(Qt.NoPen)
            p.setBrush(QColor(color))
            p.drawRoundedRect(QRectF(lx, 8, 10, 10), 3, 3)
            label = f"{name}  {self.fmt(s[-1]) if s else '–'}"
            p.setPen(QColor(TEXT))
            p.drawText(QRectF(lx + 16, 2, 260, 22), Qt.AlignLeft | Qt.AlignVCenter, label)
            lx += 26 + p.fontMetrics().width(label) + 18
        # series
        for name, color, s in self.series:
            if len(s) < 2:
                continue
            pts = [QPointF(left + i * cw / (len(s) - 1), top + ch - (v / top_v) * ch) for i, v in enumerate(s)]
            path = QPainterPath(pts[0])
            for pt in pts[1:]:
                path.lineTo(pt)
            fill = QPainterPath(path)
            fill.lineTo(left + cw, top + ch)
            fill.lineTo(left, top + ch)
            fill.closeSubpath()
            g = QLinearGradient(0, top, 0, top + ch)
            g.setColorAt(0, qc(color, 60))
            g.setColorAt(1, qc(color, 0))
            p.setPen(Qt.NoPen)
            p.fillPath(fill, QBrush(g))
            p.setPen(QPen(QColor(color), 2.2))
            p.setBrush(Qt.NoBrush)
            p.drawPath(path)
        if not vals:
            p.setPen(QColor(MUTED))
            p.drawText(QRectF(left, top, cw, ch), Qt.AlignCenter, "Collecting data… the chart fills in over the next few minutes")
        p.end()


class HourBars(QWidget):
    """Downloads and uploads per hour of today."""

    def __init__(self):
        super().__init__()
        self.down = [0] * 24
        self.up = [0] * 24
        self.setMinimumHeight(150)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    def set_data(self, down, up):
        self.down, self.up = list(down or [0] * 24), list(up or [0] * 24)
        self.update()

    def paintEvent(self, _):
        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)
        w, h = self.width(), self.height()
        left, right, top, bottom = 34, 6, 26, 22
        cw, ch = w - left - right, h - top - bottom
        small = QFont(self.font())
        small.setPixelSize(11)
        p.setFont(small)
        top_v = nice_max(max(self.down + self.up + [0]))
        for i in range(3):
            y = top + ch * i / 2
            p.setPen(QPen(QColor("#edf1f6"), 1))
            p.drawLine(QPointF(left, y), QPointF(w - right, y))
            p.setPen(QColor(MUTED))
            p.drawText(QRectF(0, y - 8, left - 6, 16), Qt.AlignRight | Qt.AlignVCenter, f"{top_v * (2 - i) / 2:g}")
        now_h = time.localtime().tm_hour
        slot = cw / 24
        bw = max(2.0, slot * 0.34)
        for hr in range(24):
            x = left + hr * slot
            if hr == now_h:
                p.setPen(Qt.NoPen)
                p.setBrush(QColor("#f1f5fb"))
                p.drawRoundedRect(QRectF(x + 1, top, slot - 2, ch), 4, 4)
            for k, (vals, color) in enumerate(((self.down, ACCENT), (self.up, ACCENT2))):
                v = vals[hr]
                if v <= 0:
                    continue
                bh = ch * v / top_v
                p.setPen(Qt.NoPen)
                p.setBrush(QColor(color))
                p.drawRoundedRect(QRectF(x + slot / 2 - bw - 1 + k * (bw + 2), top + ch - bh, bw, bh), 2, 2)
            if hr % 3 == 0:
                p.setPen(QColor(MUTED))
                p.drawText(QRectF(x - 6, h - bottom + 4, slot + 12, 16), Qt.AlignHCenter, f"{hr:02d}")
        # legend
        f = QFont(self.font())
        f.setPixelSize(12)
        f.setWeight(QFont.DemiBold)
        p.setFont(f)
        lx = left
        for name, color, total in (("Downloads", ACCENT, sum(self.down)), ("Uploads", ACCENT2, sum(self.up))):
            p.setPen(Qt.NoPen)
            p.setBrush(QColor(color))
            p.drawRoundedRect(QRectF(lx, 7, 10, 10), 3, 3)
            label = f"{name}  {total}"
            p.setPen(QColor(TEXT))
            p.drawText(QRectF(lx + 16, 1, 200, 22), Qt.AlignLeft | Qt.AlignVCenter, label)
            lx += 34 + p.fontMetrics().width(label)
        p.end()


# ---------- main window ----------

class Dashboard(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("POPFTP")
        self.setStyleSheet(STYLE)
        self.resize(1600, 900)
        self.status = {}

        root = QVBoxLayout(self)
        root.setContentsMargins(24, 18, 24, 18)
        root.setSpacing(16)

        # Header
        head = QHBoxLayout()
        brand = QLabel()
        brand.setTextFormat(Qt.RichText)
        brand.setText(f"<span style='font-size:30px; font-weight:900; letter-spacing:-1px; color:{TEXT};'>POP</span>"
                      f"<span style='font-size:30px; font-weight:900; letter-spacing:-1px; color:{ACCENT};'>FTP</span>")
        head.addWidget(brand)
        head.addSpacing(16)
        self.sub = QLabel("Waiting for data…")
        self.sub.setObjectName("sub")
        head.addWidget(self.sub, 0, Qt.AlignVCenter)
        head.addStretch(1)
        self.status_pill = QLabel("")
        head.addWidget(self.status_pill)
        self.ro_pill = QLabel("Read-only")
        self.ro_pill.setStyleSheet(f"background: #fff7ed; color: #c2410c; border: 1px solid #fed7aa; border-radius: 14px; padding: 5px 14px; font-weight: 700;")
        self.ro_pill.hide()
        head.addSpacing(8)
        head.addWidget(self.ro_pill)
        head.addSpacing(12)
        self.admin_btn = QPushButton("Admin")
        self.admin_btn.clicked.connect(self.open_admin)
        head.addWidget(self.admin_btn)
        head.addSpacing(20)
        right = QVBoxLayout()
        right.setSpacing(0)
        self.clock = QLabel("--:--:--")
        self.clock.setObjectName("clock")
        self.clock.setAlignment(Qt.AlignRight)
        self.date = QLabel("")
        self.date.setObjectName("sub")
        self.date.setAlignment(Qt.AlignRight)
        right.addWidget(self.clock)
        right.addWidget(self.date)
        head.addLayout(right)
        root.addLayout(head)

        self.banner = QLabel("")
        self.banner.setStyleSheet("background: #fef2f2; color: #b91c1c; border: 1px solid #fecaca; border-radius: 10px; padding: 8px 12px; font-weight: 600;")
        self.banner.hide()
        root.addWidget(self.banner)

        # KPI tiles
        kpis = QHBoxLayout()
        kpis.setSpacing(16)
        self.k_sessions = Kpi("Active sessions", OK)
        self.k_down = Kpi("Downloads today", ACCENT)
        self.k_up = Kpi("Uploads today", ACCENT2)
        self.k_data = Kpi("Data moved today", ACCENT)
        self.k_logins = Kpi("Logins today", MUTED)
        for k in (self.k_sessions, self.k_down, self.k_up, self.k_data, self.k_logins):
            k.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
            kpis.addWidget(k)
        root.addLayout(kpis)

        grid = QGridLayout()
        grid.setSpacing(16)

        net_frame, net_lay = panel("Network traffic", "last 60 minutes")
        self.net_chart = LineChart(human_rate)
        net_lay.addWidget(self.net_chart, 1)

        g_frame, g_lay = panel("System health")
        gg = QGridLayout()
        gg.setSpacing(6)
        self.g_cpu = Gauge("CPU")
        self.g_mem = Gauge("Memory")
        self.g_temp = Gauge("Temperature")
        self.g_disk = Gauge("Storage")
        gg.addWidget(self.g_cpu, 0, 0)
        gg.addWidget(self.g_mem, 0, 1)
        gg.addWidget(self.g_temp, 1, 0)
        gg.addWidget(self.g_disk, 1, 1)
        g_lay.addLayout(gg, 1)

        hr_frame, hr_lay = panel("Transfers by hour", "today")
        self.hours = HourBars()
        hr_lay.addWidget(self.hours, 1)

        conn_frame, conn_lay = panel("Connected clients")
        self.conn_frame = conn_frame
        self.t_conn = make_table(["Client", "Address", "User", "State", "Connected"], 0)
        conn_lay.addWidget(self.t_conn, 1)
        self.conn_empty = QLabel("No clients connected right now")
        self.conn_empty.setStyleSheet(f"color: {MUTED}; padding: 12px 0;")
        self.conn_empty.setAlignment(Qt.AlignCenter)
        conn_lay.addWidget(self.conn_empty, 1)

        act_frame, act_lay = panel("Recent activity")
        self.t_act = make_table(["Time", "Action", "File", "Size", "Speed", "Client"], 2)
        act_lay.addWidget(self.t_act, 1)

        grid.addWidget(net_frame, 0, 0, 1, 2)
        grid.addWidget(g_frame, 0, 2)
        grid.addWidget(hr_frame, 1, 0)
        grid.addWidget(conn_frame, 1, 1)
        grid.addWidget(act_frame, 1, 2)
        grid.setColumnStretch(0, 5)
        grid.setColumnStretch(1, 5)
        grid.setColumnStretch(2, 6)
        grid.setRowStretch(0, 5)
        grid.setRowStretch(1, 5)
        root.addLayout(grid, 1)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.refresh)
        self.timer.start(REFRESH_MS)
        self.clock_timer = QTimer(self)
        self.clock_timer.timeout.connect(self.tick)
        self.clock_timer.start(1000)
        self.tick()
        self.refresh()

    def open_admin(self):
        if getattr(self, "admin", None) and self.admin.isVisible():
            self.admin.raise_()
            self.admin.activateWindow()
            return
        try:
            with open(ADMIN_FILE) as f:
                cfg = json.load(f)
        except Exception:
            QMessageBox.warning(self, "Admin", "No admin password is set. Run the dashboard installer again to set one.")
            return
        pw, okd = QInputDialog.getText(self, "Admin", "Admin password:", QLineEdit.Password)
        if not okd:
            return
        h = hashlib.pbkdf2_hmac("sha256", pw.encode(), bytes.fromhex(cfg["salt"]), int(cfg["iterations"])).hex()
        if not hmac.compare_digest(h, cfg["hash"]):
            QMessageBox.warning(self, "Admin", "Wrong admin password.")
            return
        self.admin = AdminWindow(self)
        self.admin.update_status(self.status)
        self.admin.show()

    def tick(self):
        now = time.localtime()
        self.clock.setText(time.strftime("%H:%M:%S", now))
        self.date.setText(time.strftime("%A %d %B %Y", now))

    def refresh(self):
        try:
            with open(STATUS) as f:
                s = json.load(f)
        except Exception:
            self.banner.setText("No data from the background service. Check it with: systemctl status ftpdash-collector")
            self.banner.show()
            return
        self.status = s
        if getattr(self, "admin", None) and self.admin.isVisible():
            self.admin.update_status(s)
        age = time.time() - s.get("updated", 0)
        if age > 15:
            self.banner.setText(f"Data is {int(age)} seconds old. The background service may have stopped.")
            self.banner.show()
        else:
            self.banner.hide()

        self.sub.setText(f"{s.get('host', '')}  ·  {s.get('ip', '')}  ·  port {s.get('ftp_port', 21)}  ·  up {human_secs(s.get('uptime_secs'))}")
        if s.get("ftp_running"):
            self.status_pill.setText("●  Running")
            self.status_pill.setStyleSheet("background: #ecfeff; color: #0e7490; border: 1px solid #a5f3fc; border-radius: 14px; padding: 5px 14px; font-weight: 700;")
        else:
            self.status_pill.setText("●  Stopped")
            self.status_pill.setStyleSheet("background: #fef2f2; color: #b91c1c; border: 1px solid #fecaca; border-radius: 14px; padding: 5px 14px; font-weight: 700;")
        self.ro_pill.setVisible(bool(s.get("read_only")))

        t = s.get("totals", {})
        hourly = s.get("hourly", {})
        hist = s.get("history", [])
        nh = time.localtime().tm_hour + 1
        conns = s.get("connections", [])
        busy = sum(1 for c in conns if c.get("transferring"))
        self.k_sessions.set(str(len(conns)), f"{busy} transferring" if busy else "Idle",
                            [p.get("sessions", 0) for p in hist[-60:]])
        self.k_down.set(str(t.get("downloads", 0)), human_bytes(t.get("bytes_down", 0)),
                        hourly.get("downloads", [])[:nh])
        self.k_up.set(str(t.get("uploads", 0)), human_bytes(t.get("bytes_up", 0)),
                      hourly.get("uploads", [])[:nh])
        bd, bu = hourly.get("bytes_down", [0] * 24), hourly.get("bytes_up", [0] * 24)
        self.k_data.set(human_bytes(t.get("bytes_down", 0) + t.get("bytes_up", 0)),
                        f"{human_bytes(t.get('bytes_down', 0))} down · {human_bytes(t.get('bytes_up', 0))} up",
                        [a + b for a, b in zip(bd, bu)][:nh])
        failed = t.get("failed_logins", 0)
        self.k_logins.set(str(t.get("logins", 0)), f"{failed} failed" if failed else "No failed logins",
                          [], detail_color=BAD if failed else MUTED)

        # Charts
        span = len(hist) * 10
        self.net_chart.set_series([("In", ACCENT, [p.get("rx", 0) for p in hist]),
                                   ("Out", ACCENT2, [p.get("tx", 0) for p in hist])],
                                  f"{span // 60} min ago" if span >= 120 else "")
        self.hours.set_data(hourly.get("downloads"), hourly.get("uploads"))

        sysd = s.get("system", {})
        cpu = sysd.get("cpu_percent", 0)
        self.g_cpu.set(cpu, f"{cpu:.0f}%", f"load {(sysd.get('load') or [0])[0]:.2f}")
        self.g_mem.set(sysd.get("mem_percent", 0), f"{sysd.get('mem_percent', 0):.0f}%",
                       f"{human_bytes(sysd.get('mem_used', 0))} of {human_bytes(sysd.get('mem_total', 0))}")
        temp = sysd.get("temp_c")
        if temp is None:
            self.g_temp.set(0, "n/a", "")
        else:
            self.g_temp.set(temp / 85 * 100, f"{temp:.0f}°", "Celsius", warn=70 / 85 * 100, bad=80 / 85 * 100)
        disks = s.get("storage", [])
        if disks:
            d = disks[-1]  # the USB drive when attached, otherwise the SD card
            pct = 100 * (d["total"] - d["free"]) / d["total"] if d.get("total") else 0
            self.g_disk.title = d["label"]
            self.g_disk.set(pct, f"{pct:.0f}%", f"{human_bytes(d['free'])} free")

        # Connections
        self.t_conn.setRowCount(len(conns))
        for r, c in enumerate(conns):
            self.t_conn.setItem(r, 0, cell(c.get("name") or "Unnamed client"))
            self.t_conn.setItem(r, 1, cell(c.get("ip", ""), MUTED))
            self.t_conn.setItem(r, 2, cell(c.get("user", "")))
            self.t_conn.setItem(r, 3, cell("Transferring" if c.get("transferring") else "Idle",
                                           OK if c.get("transferring") else MUTED))
            self.t_conn.setItem(r, 4, cell(human_secs(c.get("connected_secs")), MUTED))
        self.conn_empty.setVisible(not conns)
        self.t_conn.setVisible(bool(conns))

        # Activity
        names = s.get("names", {})
        recent = s.get("recent", [])
        self.t_act.setRowCount(len(recent))
        for r, e in enumerate(recent):
            act = e.get("action", "").title()
            if e.get("result") == "FAIL":
                act += " failed"
            color = BAD if e.get("result") == "FAIL" else ACCENT2 if e.get("action") == "UPLOAD" else ACCENT if e.get("action") == "DOWNLOAD" else TEXT
            self.t_act.setItem(r, 0, cell(e.get("time", ""), MUTED))
            self.t_act.setItem(r, 1, cell(act, color))
            self.t_act.setItem(r, 2, cell(e.get("path", "")))
            self.t_act.setItem(r, 3, cell(human_bytes(e["bytes"]) if e.get("bytes") else "", MUTED))
            self.t_act.setItem(r, 4, cell(f"{e['rate_kbs']:.0f} KB/s" if e.get("rate_kbs") else "", MUTED))
            self.t_act.setItem(r, 5, cell(names.get(e.get("ip")) or e.get("ip", ""), MUTED))


def run_helper(args, stdin=None):
    """Run a privileged admin action. Returns (ok, message)."""
    try:
        r = subprocess.run(HELPER + args, input=stdin, capture_output=True, text=True, timeout=60)
    except Exception as e:
        return False, str(e)
    msg = (r.stdout or "").strip() if r.returncode == 0 else (r.stderr or r.stdout or "Failed.").strip()
    if "a password is required" in msg or "may not run sudo" in msg:
        msg = "Admin actions aren't allowed for this login. Run the dashboard installer again."
    return r.returncode == 0, msg


def button(text, kind=None):
    b = QPushButton(text)
    if kind:
        b.setObjectName(kind)
    return b


class AdminWindow(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        self.setWindowTitle("POPFTP: Admin")
        self.setStyleSheet(STYLE)
        self.resize(900, 640)
        self.status = {}
        self.idle = QTimer(self)
        self.idle.setSingleShot(True)
        self.idle.timeout.connect(self.lock)
        self.idle.start(ADMIN_TIMEOUT_MS)

        root = QVBoxLayout(self)
        root.setContentsMargins(18, 16, 18, 16)
        top = QHBoxLayout()
        t = QLabel("Admin")
        t.setObjectName("title")
        top.addWidget(t)
        top.addStretch(1)
        note = QLabel("Locks after 15 minutes without use")
        note.setObjectName("sub")
        top.addWidget(note)
        lockb = button("Lock")
        lockb.clicked.connect(self.lock)
        top.addWidget(lockb)
        root.addLayout(top)

        self.tabs = QTabWidget()
        root.addWidget(self.tabs, 1)
        self.tabs.addTab(self.server_tab(), "Server")
        self.tabs.addTab(self.connections_tab(), "Connections")
        self.tabs.addTab(self.devices_tab(), "Devices")
        self.tabs.addTab(self.logs_tab(), "Logs")
        self.tabs.addTab(self.system_tab(), "System")
        self.tabs.currentChanged.connect(self.touch)

    # ----- helpers -----
    def touch(self, *_):
        self.idle.start(ADMIN_TIMEOUT_MS)

    def lock(self):
        self.close()

    def confirm(self, title, text):
        self.touch()
        return QMessageBox.question(self, title, text, QMessageBox.Yes | QMessageBox.Cancel,
                                    QMessageBox.Cancel) == QMessageBox.Yes

    def act(self, args, stdin=None, quiet=False):
        self.touch()
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            okd, msg = run_helper(args, stdin)
        finally:
            QApplication.restoreOverrideCursor()
        if not okd:
            QMessageBox.warning(self, "Admin", msg)
        elif not quiet:
            QMessageBox.information(self, "Admin", msg)
        return okd, msg

    def section(self, lay, title):
        l = QLabel(title)
        l.setObjectName("panelTitle")
        l.setStyleSheet(f"color: {MUTED}; font-weight: 600; margin-top: 8px;")
        lay.addWidget(l)

    # ----- Server -----
    def server_tab(self):
        w = QWidget()
        lay = QVBoxLayout(w)
        lay.setContentsMargins(18, 14, 18, 14)
        lay.setSpacing(10)
        self.section(lay, "FTP server")
        row = QHBoxLayout()
        self.srv_state = QLabel("")
        row.addWidget(self.srv_state)
        row.addStretch(1)
        for label, cmd, kind in (("Start", "start", "primary"), ("Restart", "restart", None), ("Stop", "stop", "danger")):
            b = button(label, kind)
            b.clicked.connect(lambda _, c=cmd: self.service(c))
            row.addWidget(b)
        lay.addLayout(row)

        self.ro_check = QCheckBox("Read-only mode: block uploads, deletes and new folders")
        self.ro_check.clicked.connect(self.toggle_readonly)
        lay.addWidget(self.ro_check)

        self.section(lay, "FTP account password")
        form = QFormLayout()
        self.acct = QComboBox()
        self.pw1 = QLineEdit(); self.pw1.setEchoMode(QLineEdit.Password)
        self.pw2 = QLineEdit(); self.pw2.setEchoMode(QLineEdit.Password)
        form.addRow("Account", self.acct)
        form.addRow("New password", self.pw1)
        form.addRow("Repeat", self.pw2)
        lay.addLayout(form)
        b = button("Change password", "primary")
        b.clicked.connect(self.change_ftp_password)
        lay.addWidget(b, 0, Qt.AlignLeft)

        self.section(lay, "Admin password")
        form2 = QFormLayout()
        self.ap1 = QLineEdit(); self.ap1.setEchoMode(QLineEdit.Password)
        self.ap2 = QLineEdit(); self.ap2.setEchoMode(QLineEdit.Password)
        form2.addRow("New admin password", self.ap1)
        form2.addRow("Repeat", self.ap2)
        lay.addLayout(form2)
        b2 = button("Change admin password")
        b2.clicked.connect(self.change_admin_password)
        lay.addWidget(b2, 0, Qt.AlignLeft)
        lay.addStretch(1)
        return w

    def service(self, cmd):
        if cmd == "stop" and not self.confirm("Stop FTP server", "Stop the FTP server? Everyone connected is disconnected and nobody can connect until you start it again."):
            return
        self.act(["service", cmd])

    def toggle_readonly(self, checked):
        text = ("Turn on read-only mode? Clients can still browse and download, but can't upload, delete or create folders. "
                "The FTP server restarts, so connected clients are disconnected briefly.") if checked else \
               "Turn off read-only mode? Uploads and deletes are allowed again. The FTP server restarts briefly."
        if not self.confirm("Read-only mode", text):
            self.ro_check.setChecked(not checked)
            return
        okd, _ = self.act(["readonly", "on" if checked else "off"])
        if not okd:
            self.ro_check.setChecked(not checked)

    def change_ftp_password(self):
        if not self.acct.currentText():
            return
        if self.pw1.text() != self.pw2.text():
            QMessageBox.warning(self, "Admin", "The passwords don't match.")
            return
        okd, _ = self.act(["setpass", self.acct.currentText()], self.pw1.text() + "\n")
        if okd:
            self.pw1.clear(); self.pw2.clear()

    def change_admin_password(self):
        if self.ap1.text() != self.ap2.text():
            QMessageBox.warning(self, "Admin", "The passwords don't match.")
            return
        okd, _ = self.act(["set-admin-pass"], self.ap1.text() + "\n")
        if okd:
            self.ap1.clear(); self.ap2.clear()

    # ----- Connections -----
    def connections_tab(self):
        w = QWidget()
        lay = QVBoxLayout(w)
        lay.setContentsMargins(18, 14, 18, 14)
        self.section(lay, "Connected now")
        self.c_table = make_table(["Client", "Address", "User", "State"], 0)
        self.c_table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.c_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.c_table.itemSelectionChanged.connect(self.touch)
        lay.addWidget(self.c_table, 2)
        row = QHBoxLayout()
        kb = button("Disconnect")
        kb.clicked.connect(self.kick_selected)
        bb = button("Block", "danger")
        bb.clicked.connect(self.block_selected)
        row.addWidget(kb); row.addWidget(bb); row.addStretch(1)
        lay.addLayout(row)

        self.section(lay, "Blocked addresses")
        self.b_list = QListWidget()
        lay.addWidget(self.b_list, 1)
        row2 = QHBoxLayout()
        ub = button("Unblock selected")
        ub.clicked.connect(self.unblock_selected)
        self.b_input = QLineEdit()
        self.b_input.setPlaceholderText("Address to block, e.g. 192.168.1.30")
        ab = button("Block address", "danger")
        ab.clicked.connect(self.block_typed)
        row2.addWidget(ub); row2.addStretch(1); row2.addWidget(self.b_input, 2); row2.addWidget(ab)
        lay.addLayout(row2)
        return w

    def selected_ip(self):
        r = self.c_table.currentRow()
        if r < 0 or not self.c_table.item(r, 1):
            QMessageBox.information(self, "Admin", "Select a client in the list first.")
            return None
        return self.c_table.item(r, 1).text()

    def kick_selected(self):
        ip = self.selected_ip()
        if ip and self.confirm("Disconnect", f"Disconnect {ip}? It can connect again straight away."):
            self.act(["kick", ip])

    def block_selected(self):
        ip = self.selected_ip()
        if ip:
            self.block(ip)

    def block_typed(self):
        ip = self.b_input.text().strip()
        if ip:
            if self.block(ip):
                self.b_input.clear()

    def block(self, ip):
        if not self.confirm("Block", f"Block {ip}? It's disconnected and can't connect to the FTP server until you unblock it."):
            return False
        return self.act(["block", ip])[0]

    def unblock_selected(self):
        it = self.b_list.currentItem()
        if not it:
            QMessageBox.information(self, "Admin", "Select a blocked address first.")
            return
        self.act(["unblock", it.text()])

    # ----- Devices -----
    def devices_tab(self):
        w = QWidget()
        lay = QVBoxLayout(w)
        lay.setContentsMargins(18, 14, 18, 14)
        info = QLabel("Give each device a name so it's easy to recognise on the dashboard.")
        info.setObjectName("sub")
        lay.addWidget(info)
        self.d_table = make_table(["Address", "Name", "Seen"], 1)
        self.d_table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.d_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.d_table.itemSelectionChanged.connect(self.pick_device)
        lay.addWidget(self.d_table, 1)
        row = QHBoxLayout()
        self.d_ip = QLineEdit(); self.d_ip.setPlaceholderText("Address")
        self.d_name = QLineEdit(); self.d_name.setPlaceholderText("Name, e.g. Office PC")
        sb = button("Save name", "primary"); sb.clicked.connect(self.save_name)
        rb = button("Remove name"); rb.clicked.connect(self.remove_name)
        row.addWidget(self.d_ip, 1); row.addWidget(self.d_name, 2); row.addWidget(sb); row.addWidget(rb)
        lay.addLayout(row)
        return w

    def pick_device(self):
        self.touch()
        r = self.d_table.currentRow()
        if r >= 0 and self.d_table.item(r, 0):
            self.d_ip.setText(self.d_table.item(r, 0).text())
            self.d_name.setText(self.d_table.item(r, 1).text() if self.d_table.item(r, 1) else "")

    def save_name(self):
        ip, name = self.d_ip.text().strip(), self.d_name.text().strip()
        if ip and name:
            self.act(["name", ip] + name.split(), quiet=True)

    def remove_name(self):
        ip = self.d_ip.text().strip()
        if ip:
            self.act(["name", ip], quiet=True)
            self.d_name.clear()

    # ----- Logs -----
    def logs_tab(self):
        w = QWidget()
        lay = QVBoxLayout(w)
        lay.setContentsMargins(18, 14, 18, 14)
        row = QHBoxLayout()
        self.l_search = QLineEdit()
        self.l_search.setPlaceholderText("Search the log (file name, address, LOGIN, UPLOAD…)")
        self.l_search.textChanged.connect(self.filter_log)
        rf = button("Refresh"); rf.clicked.connect(self.load_log)
        row.addWidget(self.l_search, 1); row.addWidget(rf)
        lay.addLayout(row)
        self.l_view = QPlainTextEdit()
        self.l_view.setReadOnly(True)
        self.l_view.setLineWrapMode(QPlainTextEdit.NoWrap)
        lay.addWidget(self.l_view, 1)
        row2 = QHBoxLayout()
        self.l_count = QLabel("")
        self.l_count.setObjectName("sub")
        rt = button("Reset today's totals"); rt.clicked.connect(self.reset_totals)
        cl = button("Clear log", "danger"); cl.clicked.connect(self.clear_log)
        row2.addWidget(self.l_count); row2.addStretch(1); row2.addWidget(rt); row2.addWidget(cl)
        lay.addLayout(row2)
        self.log_lines = []
        QTimer.singleShot(0, self.load_log)
        return w

    def load_log(self):
        okd, out = run_helper(["log", "2000"])
        self.log_lines = out.splitlines() if okd else [out]
        self.filter_log()

    def filter_log(self):
        q = self.l_search.text().strip().lower()
        lines = [l for l in self.log_lines if q in l.lower()] if q else self.log_lines
        self.l_view.setPlainText("\n".join(reversed(lines)))
        self.l_count.setText(f"{len(lines)} of {len(self.log_lines)} lines, newest first")

    def reset_totals(self):
        if self.confirm("Reset totals", "Reset today's totals and the recent activity list to zero? The log itself is kept."):
            self.act(["reset-totals"])

    def clear_log(self):
        if self.confirm("Clear log", "Delete everything in the FTP log? This can't be undone. Today's totals reset too."):
            if self.act(["clear-log"])[0]:
                self.load_log()

    # ----- System -----
    def system_tab(self):
        w = QWidget()
        lay = QVBoxLayout(w)
        lay.setContentsMargins(18, 14, 18, 14)
        lay.setSpacing(12)
        for title, desc, label, handler, kind in (
            ("USB drive", "After plugging the USB drive back in.", "Re-attach drives", lambda: self.act(["remount"]), None),
            ("Background service", "If the dashboard stops updating.", "Restart service", lambda: self.act(["restart-collector"]), None),
            ("Restart the Pi", "Everyone is disconnected; back in about a minute.", "Restart Pi", self.reboot, "danger"),
            ("Shut down the Pi", "Turns the Pi off safely. Unplug only when the green light stops flashing.", "Shut down Pi", self.shutdown, "danger"),
        ):
            box = QFrame(); box.setObjectName("panel")
            bl = QHBoxLayout(box); bl.setContentsMargins(14, 10, 14, 10)
            txt = QVBoxLayout()
            a = QLabel(title); a.setStyleSheet("font-weight: 600;")
            b = QLabel(desc); b.setObjectName("sub")
            txt.addWidget(a); txt.addWidget(b)
            bl.addLayout(txt, 1)
            btn = button(label, kind); btn.clicked.connect(handler)
            bl.addWidget(btn)
            lay.addWidget(box)
        lay.addStretch(1)
        return w

    def reboot(self):
        if self.confirm("Restart the Pi", "Restart the Pi now? Everyone connected is disconnected."):
            self.act(["reboot"])

    def shutdown(self):
        if self.confirm("Shut down the Pi", "Shut down the Pi now? The FTP server stays off until the Pi is switched back on."):
            self.act(["shutdown"])

    # ----- live data -----
    def update_status(self, s):
        self.status = s or {}
        running = self.status.get("ftp_running")
        self.srv_state.setText("Running" if running else "Stopped")
        self.srv_state.setStyleSheet(f"color: {OK if running else BAD}; font-weight: 700; font-size: 16px;")
        ro = bool(self.status.get("read_only"))
        if self.ro_check.isChecked() != ro:
            self.ro_check.setChecked(ro)
        accts = self.status.get("accounts", [])
        if [self.acct.itemText(i) for i in range(self.acct.count())] != accts:
            self.acct.clear(); self.acct.addItems(accts)

        conns = self.status.get("connections", [])
        sel = self.c_table.currentRow()
        self.c_table.setRowCount(len(conns))
        for r, c in enumerate(conns):
            self.c_table.setItem(r, 0, cell(c.get("name") or "Unnamed client"))
            self.c_table.setItem(r, 1, cell(c.get("ip", "")))
            self.c_table.setItem(r, 2, cell(c.get("user", "")))
            self.c_table.setItem(r, 3, cell("Transferring" if c.get("transferring") else "Idle",
                                            OK if c.get("transferring") else MUTED))
        if 0 <= sel < len(conns):
            self.c_table.selectRow(sel)

        blocked = self.status.get("blocked", [])
        if [self.b_list.item(i).text() for i in range(self.b_list.count())] != blocked:
            self.b_list.clear(); self.b_list.addItems(blocked)

        names = self.status.get("names", {})
        seen = {c.get("ip") for c in conns}
        recent_ips = {e.get("ip") for e in self.status.get("recent", []) if e.get("ip")}
        ips = sorted(set(names) | seen | recent_ips, key=lambda x: [int(p) if p.isdigit() else p for p in x.replace(":", ".").split(".")])
        rows = [(ip, names.get(ip, ""), "Connected now" if ip in seen else "Recently" if ip in recent_ips else "") for ip in ips]
        current = [tuple(self.d_table.item(r, c).text() if self.d_table.item(r, c) else "" for c in range(3))
                   for r in range(self.d_table.rowCount())]
        if current != rows:
            sel = self.d_table.currentRow()
            self.d_table.blockSignals(True)
            self.d_table.setRowCount(len(rows))
            for r, (ip, nm, sn) in enumerate(rows):
                self.d_table.setItem(r, 0, cell(ip))
                self.d_table.setItem(r, 1, cell(nm))
                self.d_table.setItem(r, 2, cell(sn, MUTED))
            if 0 <= sel < len(rows):
                self.d_table.selectRow(sel)
            self.d_table.blockSignals(False)


def main():
    from PyQt5.QtCore import QLockFile, QDir
    lock = QLockFile(QDir.tempPath() + "/popftp.lock")
    if not lock.tryLock(100):
        sys.exit(0)  # already open
    app = QApplication(sys.argv)
    app.setApplicationName("POPFTP")
    w = Dashboard()
    w.showMaximized()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
PYEOF
sudo tee /opt/ftpdash/admin_helper.py >/dev/null <<'PYEOF'
#!/usr/bin/env python3
"""FTP Server Monitor admin helper.

Runs as root through a narrow sudo rule. Every action is checked before it runs.
Usage: admin_helper.py <action> [arguments]   (passwords are read from stdin)
"""
import hashlib
import ipaddress
import json
import os
import re
import secrets
import signal
import subprocess
import sys

CONF = "/etc/vsftpd.conf"
USERLIST = "/etc/vsftpd.userlist"
LOG = "/var/log/vsftpd.log"
ETC = "/etc/ftpdash"
NAMES = os.path.join(ETC, "names.json")
BLOCKED = os.path.join(ETC, "blocked.json")
ADMIN = os.path.join(ETC, "admin.json")
RUN = "/run/ftpdash"
FTP_PORTS = "21, 40000-40100"


def fail(msg, code=1):
    print(msg, file=sys.stderr)
    sys.exit(code)


def ok(msg="Done."):
    print(msg)
    sys.exit(0)


def run(cmd, **kw):
    return subprocess.run(cmd, capture_output=True, text=True, **kw)


def read_json(path, default):
    try:
        with open(path) as f:
            return json.load(f)
    except Exception:
        return default


def write_json(path, data, mode=0o644):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        json.dump(data, f, indent=2)
    os.chmod(tmp, mode)
    os.replace(tmp, path)


def check_ip(ip):
    try:
        return str(ipaddress.ip_address(ip))
    except ValueError:
        fail(f"Not a valid address: {ip}")


def ftp_users():
    try:
        with open(USERLIST) as f:
            return [u.strip() for u in f if u.strip() and not u.startswith("#")]
    except FileNotFoundError:
        return []


def restart_ftp():
    r = run(["systemctl", "restart", "vsftpd"])
    if r.returncode:
        fail("The FTP server did not restart:\n" + r.stderr)


# ---------- actions ----------

def a_service(args):
    if len(args) != 1 or args[0] not in ("start", "stop", "restart"):
        fail("Use: service start|stop|restart")
    r = run(["systemctl", args[0], "vsftpd"])
    if r.returncode:
        fail(r.stderr or "Failed.")
    ok({"start": "FTP server started.", "stop": "FTP server stopped.", "restart": "FTP server restarted."}[args[0]])


def a_readonly(args):
    if len(args) != 1 or args[0] not in ("on", "off"):
        fail("Use: readonly on|off")
    value = "NO" if args[0] == "on" else "YES"
    with open(CONF) as f:
        text = f.read()
    if re.search(r"^write_enable=.*$", text, flags=re.M):
        text = re.sub(r"^write_enable=.*$", f"write_enable={value}", text, flags=re.M)
    else:
        text += f"\nwrite_enable={value}\n"
    with open(CONF, "w") as f:
        f.write(text)
    restart_ftp()
    ok("Read-only mode on: uploads and deletes are blocked." if args[0] == "on"
       else "Read-only mode off: uploads and deletes are allowed.")


def a_setpass(args):
    if len(args) != 1 or args[0] not in ftp_users():
        fail("That is not an FTP account.")
    pw = sys.stdin.readline().rstrip("\n")
    if len(pw) < 4 or ":" in pw or "\n" in pw:
        fail("Password must be at least 4 characters and cannot contain ':'.")
    r = run(["chpasswd"], input=f"{args[0]}:{pw}\n")
    if r.returncode:
        fail(r.stderr or "Failed.")
    ok(f"Password changed for {args[0]}. Update it on every device that connects.")


def a_set_admin_pass(args):
    pw = sys.stdin.readline().rstrip("\n")
    if len(pw) < 4:
        fail("Admin password must be at least 4 characters.")
    salt = secrets.token_hex(16)
    iters = 200000
    h = hashlib.pbkdf2_hmac("sha256", pw.encode(), bytes.fromhex(salt), iters).hex()
    write_json(ADMIN, {"salt": salt, "iterations": iters, "hash": h})
    ok("Admin password changed.")


def ftp_session_pids(ip):
    """vsftpd processes with a connection from this address."""
    import psutil
    pids = set()
    for p in psutil.process_iter(["name"]):
        if p.info["name"] != "vsftpd":
            continue
        try:
            for c in p.net_connections(kind="inet") if hasattr(p, "net_connections") else p.connections(kind="inet"):
                if c.raddr and c.raddr.ip.replace("::ffff:", "") == ip:
                    pids.add(p.pid)
        except Exception:
            pass
    return pids


def a_kick(args):
    if len(args) != 1:
        fail("Use: kick ADDRESS")
    ip = check_ip(args[0])
    pids = ftp_session_pids(ip)
    for pid in pids:
        try:
            os.kill(pid, signal.SIGTERM)
        except ProcessLookupError:
            pass
    ok(f"Disconnected {ip}." if pids else f"{ip} has no open FTP session.")


def nft_script(ips):
    v4 = [i for i in ips if ":" not in i]
    v6 = [i for i in ips if ":" in i]
    e4 = f" elements = {{ {', '.join(v4)} }};" if v4 else ""
    e6 = f" elements = {{ {', '.join(v6)} }};" if v6 else ""
    # add, delete, re-create: reloads cleanly whether or not the table exists yet
    return (
        "table inet ftpdash\n"
        "delete table inet ftpdash\n"
        "table inet ftpdash {\n"
        f"  set blocked4 {{ type ipv4_addr;{e4} }}\n"
        f"  set blocked6 {{ type ipv6_addr;{e6} }}\n"
        "  chain input {\n"
        "    type filter hook input priority -10; policy accept;\n"
        f"    ip saddr @blocked4 tcp dport {{ {FTP_PORTS} }} drop\n"
        f"    ip6 saddr @blocked6 tcp dport {{ {FTP_PORTS} }} drop\n"
        "  }\n"
        "}\n"
    )


def apply_blocks():
    r = run(["nft", "-f", "-"], input=nft_script(read_json(BLOCKED, [])))
    if r.returncode:
        fail("Could not apply the block list:\n" + r.stderr)


def a_block(args):
    if len(args) != 1:
        fail("Use: block ADDRESS")
    ip = check_ip(args[0])
    ips = read_json(BLOCKED, [])
    if ip not in ips:
        ips.append(ip)
        write_json(BLOCKED, sorted(ips))
    apply_blocks()
    for pid in ftp_session_pids(ip):
        try:
            os.kill(pid, signal.SIGTERM)
        except ProcessLookupError:
            pass
    ok(f"Blocked {ip}. It can no longer connect to the FTP server.")


def a_unblock(args):
    if len(args) != 1:
        fail("Use: unblock ADDRESS")
    ip = check_ip(args[0])
    ips = [i for i in read_json(BLOCKED, []) if i != ip]
    write_json(BLOCKED, ips)
    apply_blocks()
    ok(f"Unblocked {ip}.")


def a_apply_blocks(args):
    apply_blocks()
    ok("Block list applied.")


def a_name(args):
    if len(args) < 1:
        fail("Use: name ADDRESS [NAME]")
    ip = check_ip(args[0])
    name = " ".join(args[1:]).strip()[:40]
    names = read_json(NAMES, {})
    if name:
        names[ip] = name
        msg = f"{ip} is now called {name}."
    else:
        names.pop(ip, None)
        msg = f"Name removed for {ip}."
    write_json(NAMES, names)
    ok(msg)


def a_log(args):
    n = 500
    if args:
        try:
            n = max(1, min(5000, int(args[0])))
        except ValueError:
            fail("Use: log [LINES]")
    try:
        with open(LOG, errors="replace") as f:
            lines = f.readlines()[-n:]
    except FileNotFoundError:
        lines = []
    sys.stdout.write("".join(lines))
    sys.exit(0)


def a_clear_log(args):
    open(LOG, "w").close()
    os.makedirs(RUN, exist_ok=True)
    open(os.path.join(RUN, "reset-totals"), "w").close()
    ok("FTP log cleared.")


def a_reset_totals(args):
    os.makedirs(RUN, exist_ok=True)
    open(os.path.join(RUN, "reset-totals"), "w").close()
    ok("Today's totals reset.")


def a_remount(args):
    r = run(["mount", "-a"])
    if r.returncode:
        fail("Could not attach drives:\n" + r.stderr)
    ok("Drives re-attached." if os.path.ismount("/home/c64/usb") else "No USB drive found. Check it's plugged in and powered.")


def a_collector(args):
    r = run(["systemctl", "restart", "ftpdash-collector"])
    if r.returncode:
        fail(r.stderr or "Failed.")
    ok("Background service restarted.")


def a_reboot(args):
    subprocess.Popen(["systemctl", "reboot"])
    ok("Restarting the Pi…")


def a_shutdown(args):
    subprocess.Popen(["systemctl", "poweroff"])
    ok("Shutting down the Pi…")


ACTIONS = {
    "service": a_service, "readonly": a_readonly, "setpass": a_setpass, "set-admin-pass": a_set_admin_pass,
    "kick": a_kick, "block": a_block, "unblock": a_unblock, "apply-blocks": a_apply_blocks,
    "name": a_name, "log": a_log, "clear-log": a_clear_log, "reset-totals": a_reset_totals,
    "remount": a_remount, "restart-collector": a_collector, "reboot": a_reboot, "shutdown": a_shutdown,
}


def main():
    if os.geteuid() != 0:
        fail("Must run as root (through sudo).")
    if len(sys.argv) < 2 or sys.argv[1] not in ACTIONS:
        fail("Unknown action. Choose one of: " + ", ".join(sorted(ACTIONS)))
    ACTIONS[sys.argv[1]](sys.argv[2:])


if __name__ == "__main__":
    main()
PYEOF
sudo chown root:root /opt/ftpdash/*.py
sudo chmod 755 /opt/ftpdash/*.py
[ -f /etc/ftpdash/names.json ] || echo '{}' | sudo tee /etc/ftpdash/names.json >/dev/null
[ -f /etc/ftpdash/blocked.json ] || echo '[]' | sudo tee /etc/ftpdash/blocked.json >/dev/null
sudo touch /var/log/vsftpd.log

echo "--- Setting up admin mode ---"
if [ -n "$ADMINPW" ]; then
  printf '%s\n' "$ADMINPW" | sudo /usr/bin/python3 /opt/ftpdash/admin_helper.py set-admin-pass >/dev/null
fi
echo "$DESKUSER ALL=(root) NOPASSWD: /usr/bin/python3 /opt/ftpdash/admin_helper.py *" | sudo tee /etc/sudoers.d/ftpdash >/dev/null
sudo chmod 440 /etc/sudoers.d/ftpdash
if ! sudo visudo -cf /etc/sudoers.d/ftpdash >/dev/null; then
  sudo rm -f /etc/sudoers.d/ftpdash
  echo "Could not set up admin permissions."
  exit 1
fi

echo "--- Starting the background service ---"
sudo tee /etc/systemd/system/ftpdash-collector.service >/dev/null <<'UNIT'
[Unit]
Description=POPFTP data collector
After=network-online.target vsftpd.service

[Service]
ExecStartPre=-/usr/bin/python3 /opt/ftpdash/admin_helper.py apply-blocks
ExecStart=/usr/bin/python3 /opt/ftpdash/collector.py
Restart=always
RestartSec=3
RuntimeDirectory=ftpdash
RuntimeDirectoryMode=0755
RuntimeDirectoryPreserve=yes

[Install]
WantedBy=multi-user.target
UNIT
sudo systemctl daemon-reload
sudo systemctl enable ftpdash-collector
sudo systemctl restart ftpdash-collector

echo "--- Adding the dashboard to the menu and to start-up ---"
sudo tee /usr/share/applications/ftp-server-monitor.desktop >/dev/null <<'DESK'
[Desktop Entry]
Type=Application
Name=POPFTP
Comment=FTP server dashboard and admin
Exec=/usr/bin/python3 /opt/ftpdash/dashboard.py
Icon=network-server
Categories=System;Monitor;
Terminal=false
DESK
sudo -u "$DESKUSER" mkdir -p "$DESKHOME/.config/autostart"
sudo -u "$DESKUSER" cp /usr/share/applications/ftp-server-monitor.desktop "$DESKHOME/.config/autostart/"
if [ -d /etc/xdg/labwc ] || command -v labwc >/dev/null 2>&1; then
  sudo -u "$DESKUSER" mkdir -p "$DESKHOME/.config/labwc"
  LW="$DESKHOME/.config/labwc/autostart"
  grep -q "/opt/ftpdash/dashboard.py" "$LW" 2>/dev/null || \
    echo "/usr/bin/python3 /opt/ftpdash/dashboard.py &" | sudo -u "$DESKUSER" tee -a "$LW" >/dev/null
fi

echo "--- Closing any open dashboard window (it reopens after the restart) ---"
pkill -f /opt/ftpdash/dashboard.py 2>/dev/null || true

echo "--- Logging in to the desktop automatically ---"
sudo raspi-config nonint do_boot_behaviour B4 || true

echo
echo "=== Done! ==="
echo "Restart the Pi to see POPFTP:  sudo reboot"
echo "Admin mode: click Admin on the dashboard and enter your admin password."
