#!/bin/bash
# Shared helpers for the EdNovas fnOS lifecycle scripts (sourced by cmd/*).
#
# App Center runs these as root (config/privilege: run-as root). The real
# service is our own systemd unit (target/scripts/ednovas.service); these
# scripts only install, start, stop and remove it.

APP=ednovas
APP_DIR="/var/apps/$APP"
TARGET="${TRIM_APPDEST:-$APP_DIR/target}"
VAR="${TRIM_PKGVAR:-$APP_DIR/var}"
UNIT=ednovas.service
UNIT_PATH="/etc/systemd/system/$UNIT"
LOG="$VAR/lifecycle.log"
SCRIPT="$(basename "$0")"
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin${PATH:+:$PATH}"
export PATH

log() {
	mkdir -p "$VAR" 2>/dev/null
	printf '%s [%s] %s\n' "$(date '+%F %T')" "$SCRIPT" "$*" >>"$LOG" 2>/dev/null
}

# user_msg: a line App Center may show to the user (install/start errors).
user_msg() {
	log "user message: $*"
	[ -n "${TRIM_TEMP_LOGFILE:-}" ] && printf '%s\n' "$*" >"$TRIM_TEMP_LOGFILE" 2>/dev/null
	return 0
}

# require_root: everything EdNovas does on a NAS (tun device, routing,
# firewall, ip_forward) needs root. Without it the app could only offer a
# plain HTTP/SOCKS proxy, so refuse loudly instead of half-working.
require_root() {
	if [ "$(id -u)" != "0" ]; then
		user_msg "EdNovas 需要以 root 身份运行（当前 uid=$(id -u)），无法设置透明代理。"
		return 1
	fi
	return 0
}

# fix_modes: packaging tools may store files as 0666; restore exec bits.
fix_modes() {
	chmod 0755 "$TARGET"/bin/* "$TARGET"/scripts/*.sh 2>/dev/null
	chmod 0755 "$APP_DIR"/cmd/* 2>/dev/null
	return 0
}

# install_unit copies the shipped unit into place when it changed.
install_unit() {
	fix_modes
	if ! cmp -s "$TARGET/scripts/$UNIT" "$UNIT_PATH" 2>/dev/null; then
		install -m 0644 "$TARGET/scripts/$UNIT" "$UNIT_PATH" || return 1
		systemctl daemon-reload
		log "unit installed"
	fi
	return 0
}

# remove_unit stops and deletes the unit, then clears any leftover rules.
remove_unit() {
	systemctl disable --now "$UNIT" >>"$LOG" 2>&1
	rm -f "$UNIT_PATH"
	systemctl daemon-reload
	[ -f "$TARGET/scripts/cleanup.sh" ] && sh "$TARGET/scripts/cleanup.sh"
	log "unit removed"
	return 0
}

unit_active() {
	systemctl is-active --quiet "$UNIT"
}
