# Only the first installation sets defaults. Upgrades leave services and sign-in choices alone.

# The live image (iso/profile/airootfs/etc/starchaser-live-image) installs this package on the build computer: it
# signs the live account in on the console, and its firewall would be set up from the build computer's network.
_live_image() { [ -e /etc/starchaser-live-image ]; }

post_install() {
  local share=/usr/share/starchaser
  # The filesystem package owns Arch's os-release symlink; use the setup's NoExtract rule.
  if [ "$(. /etc/os-release; echo "$ID")" = arch ]; then
    rm -f /etc/os-release
    install -m644 "$share/system/etc/os-release" /etc/os-release
    grep -q '^NoExtract.*etc/os-release' /etc/pacman.conf || \
      sed -i '/^\[options\]/a NoExtract = etc/os-release' /etc/pacman.conf
  fi
  install -d -o greeter -g greeter -m700 /var/lib/starchaser/greeter-home
  # Only replace greetd's untouched package default; keep an existing login setup.
  if ! _live_image && python3 - <<'PY'
import hashlib
from pathlib import Path
config = Path('/etc/greetd/config.toml')
if not config.exists():
    raise SystemExit(0)
for files in Path('/var/lib/pacman/local').glob('greetd-[0-9]*/files'):
    for line in files.read_text().splitlines():
        if line.startswith('etc/greetd/config.toml\t'):
            raise SystemExit(hashlib.md5(config.read_bytes()).hexdigest() != line.split('\t')[1])
raise SystemExit(1)
PY
  then
    install -Dm644 "$share/system/etc/greetd/config.toml" /etc/greetd/config.toml
    if [ ! -e /etc/systemd/system/display-manager.service ]; then
      systemctl enable greetd.service 2>/dev/null || true
    fi
  fi
  # Enable for next boot; installing from an existing desktop must not interrupt its network or session.
  systemctl enable NetworkManager.service bluetooth.service power-profiles-daemon.service \
    avahi-daemon.service starchaser-firewall-stats.timer starchaser-route-guard.service 2>/dev/null || true
  _live_image || /usr/local/lib/starchaser/starchaser-admin firewall-default-on >/dev/null || \
    echo '  The firewall could not be turned on. Open Settings > Firewall to check it.'
  echo '  Starchaser is installed. Restart, then sign in to the Starchaser session.'
}
