#!/bin/sh /etc/rc.common
# SecuBox Gitea Platform - Self-hosted Git service
# Copyright (C) 2025 CyberMind.fr

START=95
STOP=10
USE_PROCD=1

PROG=/usr/sbin/giteactl
CONFIG=gitea
LXC_NAME="gitea"
LXC_PATH="/srv/lxc"

is_installed() {
	[ -f "$LXC_PATH/$LXC_NAME/config" ] && [ -d "$LXC_PATH/$LXC_NAME/rootfs" ]
}

is_running() {
	lxc-info -n "$LXC_NAME" -s 2>/dev/null | grep -q "RUNNING"
}

start_service() {
	local enabled
	config_load "$CONFIG"
	config_get enabled main enabled '0'

	[ "$enabled" = "1" ] || {
		echo "Gitea is disabled. Enable with: uci set gitea.main.enabled=1 && uci commit gitea"
		return 0
	}

	if ! is_installed; then
		echo "Gitea not installed. Run: giteactl install"
		return 1
	fi

	procd_open_instance
	procd_set_param command "$PROG" service-run
	procd_set_param respawn 3600 5 5
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

stop_service() {
	"$PROG" service-stop
}

service_triggers() {
	procd_add_reload_trigger "$CONFIG"
}

reload_service() {
	stop
	start
}

status_service() {
	if is_running; then
		echo "running"
		return 0
	else
		echo "not running"
		# Show why
		local enabled
		config_load "$CONFIG"
		config_get enabled main enabled '0'
		[ "$enabled" = "1" ] || echo "  (disabled in config)"
		is_installed || echo "  (not installed - run: giteactl install)"
		return 1
	fi
}
