#!/bin/bash
# Install Verae Timestamping print destination for the console user.
set -euo pipefail

LOG="/var/log/verae-print-pkg-postinstall.log"
exec >>"$LOG" 2>&1
echo "$(date -u +%Y-%m-%dT%H:%MZ) postinstall start"

BIN="/Library/Application Support/Verae/PrintStamp/bin/verae-print"
SUPPORT="/Library/Application Support/Verae/PrintStamp"
APP="/Applications/Verae Print Stamp.app"

# Symlink CLI onto PATH
mkdir -p /usr/local/bin
ln -sf "$BIN" /usr/local/bin/verae-print

# Install Destination printer for the logged-in GUI user
CONSOLE_USER=$(stat -f%Su /dev/console 2>/dev/null || true)
if [[ -z "$CONSOLE_USER" || "$CONSOLE_USER" == "root" || "$CONSOLE_USER" == "_mbsetupuser" ]]; then
  CONSOLE_USER=$(scutil <<< "show State:/Users/ConsoleUser" 2>/dev/null | awk '/Name :/ && $3 != "loginwindow" { print $3 }' || true)
fi

if [[ -n "${CONSOLE_USER:-}" && "$CONSOLE_USER" != "root" ]]; then
  HOME_DIR=$(dscl . -read "/Users/$CONSOLE_USER" NFSHomeDirectory 2>/dev/null | awk '{print $2}')
  if [[ -n "$HOME_DIR" && -d "$HOME_DIR" ]]; then
    export HOME="$HOME_DIR"
    export USER="$CONSOLE_USER"
    export VERAE_PRINT_BIN="$BIN"
    # Copy install script helpers into user support and run as that user
    USER_SUPPORT="$HOME_DIR/Library/Application Support/Verae/ipp-printer"
    mkdir -p "$USER_SUPPORT/spool"
    cp -f "$SUPPORT/ipp/verae-print-command.sh" "$USER_SUPPORT/verae-print-command.sh"
    chmod 755 "$USER_SUPPORT/verae-print-command.sh"
    chown -R "$CONSOLE_USER" "$HOME_DIR/Library/Application Support/Verae" || true

    # Materialize LaunchAgent
    PLIST_SRC="$SUPPORT/ipp/com.verae.timestamping.ipp.plist"
    PLIST_DST="$HOME_DIR/Library/LaunchAgents/com.verae.timestamping.ipp.plist"
    mkdir -p "$HOME_DIR/Library/LaunchAgents"
    sed "s|/Users/SHARED_PLACEHOLDER|$USER_SUPPORT|g" "$PLIST_SRC" >"$PLIST_DST"
    # Point -c at user command; bake verae-print path into command script
    sed -i '' "s|VERAE_PRINT_BIN:-\$HOME/bin/verae-print|VERAE_PRINT_BIN:-$BIN|" "$USER_SUPPORT/verae-print-command.sh" 2>/dev/null || true
    chown "$CONSOLE_USER" "$PLIST_DST"

    UID_NUM=$(id -u "$CONSOLE_USER")
    launchctl bootout "gui/$UID_NUM/com.verae.timestamping.ipp" 2>/dev/null || true
    sudo -u "$CONSOLE_USER" launchctl bootstrap "gui/$UID_NUM" "$PLIST_DST" 2>/dev/null \
      || sudo -u "$CONSOLE_USER" launchctl load -w "$PLIST_DST" 2>/dev/null \
      || true

    sleep 1
    # Register CUPS queue if IPP is up
    if curl -sf -o /dev/null --max-time 2 "http://127.0.0.1:8631/" 2>/dev/null; then
      lpadmin -p Verae_Timestamping -E \
        -v "ipp://127.0.0.1:8631/ipp/print" \
        -D "Verae Timestamping" \
        -L "Digests-only Verae timestamp" \
        -m everywhere 2>/dev/null || true
      cupsenable Verae_Timestamping 2>/dev/null || true
      cupsaccept Verae_Timestamping 2>/dev/null || true
    fi
  fi
fi

echo "$(date -u +%Y-%m-%dT%H:%MZ) postinstall done"
exit 0
