#!/bin/sh
# sg-mail -- start SG Mail: Thunderbird with SG Mail's own profile, whose
# main window our extension makes SG Mail's (an Outlook-style window).
#
#   sg-mail                     the main window (or bring the running one up)
#   sg-mail mailto:ADDR?...     a new message (SG Mail's message window)
#   sg-mail FILE.eml|FILE.ics   open a message / import a calendar file
#
# The profile is SG Mail's alone ($SG_MAIL_PROFILE, default
# $XDG_DATA_HOME/sg-mail/profile); a person's own Thunderbird profile is not
# touched. Each start lays our extension and settings into it (a package
# upgrade reaches it this way). A second start hands its arguments to the
# running one (Thunderbird's remote service: same --name and profile).
#
# Copyright (C) 2026 Stained Glass OS contributors
# SPDX-License-Identifier: AGPL-3.0-or-later
set -eu
SHARE=${SG_MAIL_SHARE:-/usr/share/sg-mail}
EXT_ID=sg-mail@stained-glass-os.org
PROFILE=${SG_MAIL_PROFILE:-${XDG_DATA_HOME:-$HOME/.local/share}/sg-mail/profile}
TB=${SG_MAIL_THUNDERBIRD:-thunderbird}

umask 077
mkdir -p "$PROFILE/extensions"
# our extension: replaced when the package brought a new one
xpi="$PROFILE/extensions/$EXT_ID.xpi"
if ! cmp -s "$SHARE/$EXT_ID.xpi" "$xpi" 2>/dev/null; then
    cp "$SHARE/$EXT_ID.xpi" "$xpi.new" && mv -f "$xpi.new" "$xpi"
    # Thunderbird notices a changed add-on on its next start; forget its
    # startup cache so it does not keep the old one
    rm -f "$PROFILE/addonStartup.json.lz4" "$PROFILE/startupCache/"* 2>/dev/null || :
fi
# no glimpse of Thunderbird's own view before SG Mail's window is up
mkdir -p "$PROFILE/chrome"
cp "$SHARE/userChrome.css" "$PROFILE/chrome/userChrome.css" 2>/dev/null || :
# SG Mail's settings (user.js wins over what the profile keeps), then a
# system policy's (an administrator's /etc/sg-mail/user.js), if any
{
    cat "$SHARE/user.js"
    [ ! -r "${SG_MAIL_POLICY:-/etc/sg-mail/user.js}" ] || cat "${SG_MAIL_POLICY:-/etc/sg-mail/user.js}"
} > "$PROFILE/user.js.new" && mv -f "$PROFILE/user.js.new" "$PROFILE/user.js"

# Stained Glass OS's session shows X11 windows on its taskbar (XWayland)
if [ -n "${DISPLAY:-}" ]; then
    export MOZ_ENABLE_WAYLAND=0 GDK_BACKEND=x11
fi

# Microsoft calendars and contacts: each account's DavMail gateway (a user
# service), up before Thunderbird asks it for anything
DAVMAIL_HELPER=${SG_MAIL_DAVMAIL_HELPER:-/usr/lib/sg-mail/sg-mail-davmail}
if [ -x "$DAVMAIL_HELPER" ]; then
    "$DAVMAIL_HELPER" start-all >/dev/null 2>&1 || :
fi

for a in "$@"; do
    case "$a" in
        --help|-h)
            sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'
            exit 0 ;;
    esac
done
# Thunderbird draws its window itself and scales by GTK's whole-number
# factor: sg-image's GTK (gtk-scale, a fractional display scale such as
# 175%) tells such programs scale 1 and the whole DPI -- it knows Thunderbird
# by its program name, and started as sg-mail (--name) it took SG Mail for
# an ordinary GTK program. At 175% SG Mail's page then ran off the window's
# right and bottom edges (the navigation bar and status bar gone) and every
# click landed 1/7 further right and lower than the pointer (regression walk
# 2026-10-06). GDK_SG_FRACTIONAL=0 says what it is.
export GDK_SG_FRACTIONAL=0
# A Thunderbird still ending holds the profile's lock: started again in those
# seconds (File > Exit or Ctrl+Q, then SG Mail from Start at once) it said
# "Thunderbird is already running, but is not responding" (regression walk
# 2026-10-06). The lock names its process; one with no window left is
# ending: wait for it (15 s at most). One with a window is running, and gets
# this start's request (Thunderbird's remote service).
lockpid=$(readlink "$PROFILE/lock" 2>/dev/null | sed -n 's/.*:+\{0,1\}\([0-9][0-9]*\)$/\1/p')
if [ -n "$lockpid" ] && kill -0 "$lockpid" 2>/dev/null; then
    XDT=${SG_MAIL_XDOTOOL:-xdotool}
    if command -v "$XDT" >/dev/null 2>&1 && [ -n "${DISPLAY:-}" ] && [ -z "$("$XDT" search --onlyvisible --pid "$lockpid" 2>/dev/null)" ]; then
        i=0
        while kill -0 "$lockpid" 2>/dev/null && [ $i -lt 150 ]; do sleep 0.1; i=$((i + 1)); done
    fi
fi
exec "$TB" --name sg-mail --class sg-mail --profile "$PROFILE" "$@"
