#!/bin/sh
# postinst — twiy package ONLY (twiy-raweb uses postinst-raweb).
#
# Config files live under /nginx but are NOT tracked by dpkg. The package
# ships an empty /nginx skeleton (so dpkg keeps the dirs across upgrades) plus
# a pristine copy of every config under /usr/share/twiy/defaults/nginx.
#
# Config policy for twiy:
#   - target present (identical OR admin-edited) -> NEVER replace; leave as-is.
#   - target absent, FRESH INSTALL               -> create it, no questions.
#                                                  /nginx is empty by design on
#                                                  a fresh install, so asking
#                                                  would mean one Y/N per file
#                                                  and a noninteractive install
#                                                  would end up with no config
#                                                  at all (nginx then fails to
#                                                  start).
#   - target absent, UPGRADE                     -> the admin deleted it on
#                                                  purpose, so ASK (per file,
#                                                  Y/N) and only create on Y.
# We never drop <file>.new and we never overwrite an existing config, so an
# upgrade can never change an admin-edited config.
#
# TWIY_SEED_DEFAULTS overrides the upgrade behaviour for automation:
#   yes -> create every missing default without asking
#   no  -> never create a missing default
#
# /hostdata is left entirely to the admin: we only make sure the dir exists,
# and we never touch or remove its contents.

set -e

# Ask the admin a yes/no question on the controlling terminal. Defaults to
# "no" (return 1) whenever we cannot prompt — noninteractive frontend or no
# usable terminal — so a config is never created without explicit consent.
prompt_yes_no() {
    msg="$1"
    if [ "${DEBIAN_FRONTEND:-}" = noninteractive ] || [ ! -r /dev/tty ]; then
        echo "twiy: $msg -> skipped (noninteractive)"
        return 1
    fi
    printf 'twiy: %s [y/N] ' "$msg" > /dev/tty
    read ans < /dev/tty || ans=""
    case "$ans" in
        [Yy]|[Yy][Ee][Ss]) return 0 ;;
        *) return 1 ;;
    esac
}

# dpkg calls us as `postinst configure <old-version>`; $2 is empty only on a
# fresh install (or on reinstall after a purge), which is exactly the case where
# an empty /nginx is expected rather than admin intent.
if [ "$1" = configure ] && [ -z "${2:-}" ]; then
    fresh_install=yes
else
    fresh_install=no
fi

useradd -r -s /bin/false nginx 2>/dev/null || true

# Existing dirs are left exactly as they are (mkdir -p is a no-op then).
mkdir -p /nginx /hostdata

# Migration: older releases shipped /nginx/* as dpkg-tracked files, so the
# upgrade unpack deletes them before this script runs. preinst stashed a copy
# first — restore the admin's own files now, without clobbering anything
# already present (cp -n). This only puts back what dpkg removed; it never
# introduces new packaged defaults, so no prompt is needed here.
if [ -d /var/backups/twiy-nginx ]; then
    cp -an /var/backups/twiy-nginx/. /nginx/ 2>/dev/null || true
    rm -rf /var/backups/twiy-nginx
fi

# Should a missing config be created? Fresh install and TWIY_SEED_DEFAULTS
# answer without touching the terminal; an upgrade asks the admin per file.
seed_missing() {
    dst="$1"
    case "${TWIY_SEED_DEFAULTS:-}" in
        [Yy]|[Yy][Ee][Ss]) return 0 ;;
        [Nn]|[Nn][Oo])     return 1 ;;
    esac
    [ "$fresh_install" = yes ] && return 0
    prompt_yes_no "config '$dst' does not exist. Create it from the packaged default?"
}

# Seed packaged defaults:
#   - target present  -> do nothing (never replace, no .new).
#   - target absent   -> seed_missing decides (see the policy note above).
seed_tree() {
    stash="$1"
    target="$2"
    [ -d "$stash" ] || return 0
    find "$stash" -type f | while IFS= read -r src; do
        rel=${src#$stash/}
        dst="$target/$rel"
        if [ -e "$dst" ]; then
            continue
        fi
        if seed_missing "$dst"; then
            install -d "$(dirname "$dst")"
            cp -p "$src" "$dst"
            echo "twiy: created $dst"
        else
            echo "twiy: skipped $dst"
        fi
    done
}
seed_tree /usr/share/twiy/defaults/nginx /nginx

install -d /nginx/conf.d /nginx/config
install -d -o nginx -g nginx -m 0755 /var/log/nginx
chown -R nginx:nginx /var/log/nginx /nginx 2>/dev/null || true

systemctl daemon-reload  2>/dev/null || true
systemctl enable  nginx.service 2>/dev/null || true
systemctl restart nginx.service 2>/dev/null || true

exit 0
