# starchaser-desktop: the steps after pacman puts the files in place (the same ones the desktop setup does)

# The live image (iso/profile/airootfs/etc/starchaser-live-image) is built by installing this package on the build
# computer. Steps that record or change the computer they run on skip there: the image would carry the build
# computer's state to every stick, and the build computer's own kernel settings and programs would be changed.
_live_image() { [ -e /etc/starchaser-live-image ]; }

_apply() {
  # Always refresh installed services and package-owned integration; one-time changes live in migrations/.
  /usr/share/starchaser/bin/starchaser-migrate system "${@}" ||
    echo "A one-time update step did not finish. Starchaser will try it again at the next update or sign-in." >&2
  # A custom SSH session hook stays the person's own. Default sessions record the authenticated public key.
  if [ ! -e /etc/ssh/sshrc ] || grep -qF '# Starchaser records' /etc/ssh/sshrc; then
    install -Dm644 -o root -g root /usr/share/starchaser/system/etc/ssh/sshrc /etc/ssh/sshrc
  fi
  # ExposeAuthInfo is read globally, without changing the account-specific password policy.
  printf '%s\n' 'ExposeAuthInfo yes' > /etc/ssh/sshd_config.d/00-starchaser-signin-info.conf
  sshd -t && systemctl reload sshd 2>/dev/null || true
  # Use the installed authentication stack with a separate network failure tally.
  python3 /usr/local/lib/starchaser/network_pam.py || return 1
  # the password prompt's own PAM stack: Arch's, except that closing the prompt isn't counted as a wrong password
  # (the polkit package owns this file and keeps a changed copy, so it is copied, not shipped)
  if ! cmp -s /usr/share/starchaser/system/etc/pam.d/polkit-1 /etc/pam.d/polkit-1; then
    install -m644 -o root -g root /usr/share/starchaser/system/etc/pam.d/polkit-1 /etc/pam.d/polkit-1
  fi
  # wrong passwords: 5 tries, then a 30-second wait (Arch's pam package owns faillock.conf, so it is copied, and only
  # over Arch's unchanged file or Starchaser's own; a file with the person's own settings stays)
  /usr/local/lib/starchaser/starchaser-faillock-conf /usr/share/starchaser/system/etc/security/faillock.conf /etc/security/faillock.conf || true
  /usr/local/lib/starchaser/starchaser-local-auth refresh || return 1
  # the print dialog lists printers and Print to File, not "Print to LPR"; a personal settings.ini wins key by key.
  # Copied, not shipped: setups before the package left their own copies, which a newly owned path would turn into
  # "conflicting files" for the plain pacman -Su of an older updater.
  for v in 3 4; do
    f=/usr/share/starchaser/system/etc/xdg/gtk-$v.0/settings.ini
    [ -f "$f" ] && ! cmp -s "$f" /etc/xdg/gtk-$v.0/settings.ini && install -Dm644 -o root -g root "$f" /etc/xdg/gtk-$v.0/settings.ini
  done
  # the Document Viewer prints from its own dialog, which reads that list and names the file after the document, not
  # from the portal's; copied, not shipped, for the same reason
  f=/usr/share/starchaser/system/usr/local/bin/hyprland-dialog
  [ -f "$f" ] && ! cmp -s "$f" /usr/local/bin/hyprland-dialog && install -Dm755 -o root -g root "$f" /usr/local/bin/hyprland-dialog
  f=/usr/share/starchaser/system/usr/local/bin/mousepad
  [ -f "$f" ] && ! cmp -s "$f" /usr/local/bin/mousepad && install -Dm755 -o root -g root "$f" /usr/local/bin/mousepad
  f=/usr/share/starchaser/system/usr/local/bin/papers
  [ -f "$f" ] && ! cmp -s "$f" /usr/local/bin/papers && install -Dm755 -o root -g root "$f" /usr/local/bin/papers
  [ -f /etc/pam.d/greetd ] && install -Dm644 /usr/share/starchaser/system/etc/pam.d/greetd /etc/pam.d/greetd
  # sudo's own settings (it passes on the "account is paused" note), then the login screen's "is this account
  # paused?" and "Use my recovery code" questions; copied, not shipped, like the
  # setup does, and only when sudo accepts the rule (a bad file in sudoers.d would break sudo for everyone)
  for r in 05-starchaser-defaults 20-starchaser-first-start 20-starchaser-switch-user 20-starchaser-greeter-pause 20-starchaser-greeter-recovery-code; do
    f=/usr/share/starchaser/system/etc/sudoers.d/$r
    [ -f "$f" ] && ! cmp -s "$f" /etc/sudoers.d/$r && visudo -cqf "$f" && install -Dm440 -o root -g root "$f" /etc/sudoers.d/$r
  done
  # network hardening the firewall relies on
  # (in an image build the kernel is the build computer's)
  _live_image || /usr/lib/systemd/systemd-sysctl /etc/sysctl.d/60-starchaser-net.conf 2>/dev/null || true
  # the firewall's units (they live in /etc, which pacman's own reload hook doesn't watch)
  systemctl daemon-reload 2>/dev/null || true
  systemctl enable --now starchaser-power-policy.service 2>/dev/null || true
  systemctl restart starchaser-power-policy.service 2>/dev/null || true

  systemctl enable starchaser-pacman-repair.service 2>/dev/null || true
  systemctl enable starchaser-lts-good.service 2>/dev/null || true
  systemctl enable --now starchaser-planned-restart.service 2>/dev/null || true
  # the newest snapshots in the boot menu, updated when snapshots come and go, and a go-back chosen from one of them
  systemctl enable starchaser-boot-snapshots.service starchaser-snapshot-go-back.service 2>/dev/null || true
  systemctl reset-failed starchaser-boot-snapshots.service starchaser-boot-snapshots.path 2>/dev/null || true
  systemctl enable --now starchaser-boot-snapshots.path 2>/dev/null || true
  systemctl enable --now starchaser-fleet-safety.socket 2>/dev/null || true
  # fleet v2: inert unless /etc/starchaser/fleet-v2-preview exists (its units' condition)
  systemctl enable starchaser-fleet-root.socket starchaser-fleet-people.socket starchaser-fleet-state.service starchaser-fleet-firstboot.service starchaser-fleet-renumber.service 2>/dev/null || true
  systemctl try-restart starchaser-fleet-safety.service 2>/dev/null || true
  systemctl try-restart starchaser-usb-lock.service 2>/dev/null || true
  systemctl enable --now starchaser-home-versions.timer starchaser-drive-health.timer 2>/dev/null || true
  systemctl enable --now starchaser-firewall-authorization.socket 2>/dev/null || true
  systemctl try-restart starchaser-firewall-authorization.service 2>/dev/null || true
  systemctl enable --now starchaser-scheduler.timer 2>/dev/null || true
  python3 -c 'import sys; sys.path.insert(0, "/usr/local/lib/starchaser"); import update_health; update_health.migrate()' || echo "  The update startup check could not be prepared."
  systemctl enable starchaser-update-health.service 2>/dev/null || true
  systemctl enable --now starchaser-update-download.timer 2>/dev/null || true
  systemctl enable --now starchaser-update-restart.timer 2>/dev/null || true
  # Mission Control and Settings > Security read its report; it only reads the package lists and installs nothing
  systemctl enable --now starchaser-vulnerabilities.timer 2>/dev/null || true
  # Settings > Printers: CUPS starts only when something prints (its socket), and printer discovery is limited to
  # networks you trust from now on, not only after the next network change
  systemctl enable --now cups.socket 2>/dev/null || true
  systemctl enable --now starchaser-pdf-printer.service 2>/dev/null || echo "  Save as PDF could not be prepared; check printing in Settings > Printers."
  [ -f /etc/starchaser/policy.json ] && /usr/local/lib/starchaser/starchaser-admin firewall-zones-refresh >/dev/null 2>&1 || true
  # Upgrade existing protection's access boundary without changing its selected level. Only a rules file the setup
  # wrote counts: the usbguard package ships it empty. A first run here would remember the devices of whatever
  # computer runs this step and block every other one. The 1.0.29 live image was built that way: it carried the
  # build computer's devices and blocked the USB stick it started from, so every sign-in failed ("Module is unknown").
  # The live image never records devices: it masks usbguard, and its stick runs on computers the build never saw.
  if ! _live_image && [ -s /etc/usbguard/rules.conf ]; then
    /usr/local/lib/starchaser/starchaser-admin usb-setup >/dev/null 2>&1 || echo "  USB protection needs attention in Settings > Privacy."
  fi
  # The saved choice survives package upgrades; a new install's default level comes from the desktop setup.
  if python3 -c 'import sys; sys.path.insert(0, "/usr/local/lib/starchaser"); import updater; sys.exit(updater.read_level()["level"] == "off")'; then
    systemctl enable --now starchaser-autoupdate.timer 2>/dev/null || true
  fi
  if [ -f /etc/snapper/configs/root ]; then
    systemctl enable --now starchaser-update-snapshots.timer 2>/dev/null || true
  fi
  for policy in etc/snapper/filters/starchaser.txt etc/polkit-1/rules.d/50-starchaser-software.rules; do
    install -Dm644 -o root -g root "/usr/share/starchaser/system/$policy" "/$policy"
  done
  # a running snapperd keeps the filters it read at start: the next go-back starts it again with the new list
  # (in an image build pkill would see the build computer's own processes)
  _live_image || pkill -x snapperd 2>/dev/null || true
  # firewall rules saved by an older version are compiled again from the unchanged policy (does nothing when the
  # firewall is off, the saved rules are current, or a change is waiting for Keep)
  /usr/local/lib/starchaser/starchaser-admin firewall-upgrade >/dev/null 2>&1 || true
  # Mission Control: no "web console" lines in terminals, the upstream pages hidden behind it, and what the person
  # turned on written again with the new files (nothing is turned on)
  systemd-tmpfiles --create /etc/tmpfiles.d/cockpit-ws.conf 2>/dev/null || true
  systemd-tmpfiles --create /etc/tmpfiles.d/starchaser-login-remote.conf 2>/dev/null || true
  /usr/local/lib/starchaser/starchaser-mission-control-admin sync-overrides >/dev/null 2>&1 || true
  /usr/local/lib/starchaser/starchaser-mission-control-admin refresh >/dev/null 2>&1 || true
}

post_install() {
  # The setup configures current defaults; fresh installs have no old settings to migrate.
  # Switching a previously set-up checkout to the package is an upgrade too.
  if [ -e /etc/starchaser/updates.json ]; then
    _apply || return 1
  else
    _apply --mark-current || return 1
  fi
  echo "  Starchaser's files are installed in /usr/share/starchaser. A desktop set up from it (the setup run with"
  echo "  REPO=/usr/share/starchaser) refreshes each person's own copies at their next sign-in or update."
}

# The "Starchaser Linux N is installed" screen is about a new version on a computer that had an earlier one, so only
# an upgrade that changes the version records it; a first install (a new computer, the live stick) never does.
# root:wheel 2775: the first administrator who closes the screen marks it seen for the whole computer.
_record_release_update() {
  _live_image && return 0
  new=${1%-*}; old=${2%-*}
  [ -n "$old" ] && [ "$new" != "$old" ] || return 0
  d=/var/lib/starchaser/release-notice
  install -d -m 2775 -o root -g wheel "$d" || return 0
  printf '{"from": "%s", "to": "%s"}\n' "$old" "$new" > "$d/.updated.$$.tmp" && mv -f "$d/.updated.$$.tmp" "$d/updated"
}

post_upgrade() {
  _apply || return 1
  _record_release_update "$1" "$2" || true
}
