#!/bin/sh /etc/rc.common
# Copyright (C) 2021-2022 Gerald Kerma <gandalf@gk2.net>

START=99
USE_PROCD=1
NAME=crowdsec
PROG=/usr/bin/crowdsec
CONFIG=/etc/crowdsec/config.yaml
RUNCONFDIR=/srv/crowdsec/data
VARCONFIGDIR=/var/etc/crowdsec
VARCONFIG=/var/etc/crowdsec/config.yaml

service_triggers() {
	procd_add_reload_trigger crowdsec
}

setup_syslog() {
	# CrowdSec needs log files to exist for acquisition
	# OpenWrt uses logd by default which doesn't write to files
	# Enable file logging so CrowdSec can read from /var/log/messages

	local log_file
	log_file=$(uci -q get system.@system[0].log_file)

	if [ -z "$log_file" ]; then
		logger -t crowdsec "Enabling syslog file logging for CrowdSec acquisition"
		uci set system.@system[0].log_file='/var/log/messages'
		uci set system.@system[0].log_size='512'
		uci commit system
		/etc/init.d/log restart
		# Wait for log file to be created
		sleep 2
	fi

	# Ensure log file exists
	if [ ! -f /var/log/messages ]; then
		touch /var/log/messages
		chmod 644 /var/log/messages
	fi
}

init_config() {
	config_load crowdsec
	config_get data_dir crowdsec data_dir "${RUNCONFDIR}"
	config_get db_path crowdsec db_path "${RUNCONFDIR}/crowdsec.db"

	# Create tmp dir & permissions if needed
	if [ ! -d "${VARCONFIGDIR}" ]; then
		mkdir -m 0755 -p "${VARCONFIGDIR}"
	fi;

	cp $CONFIG $VARCONFIG

	sed -i "s,^\(\s*data_dir\s*:\s*\).*\$,\1$data_dir," $VARCONFIG
	sed -i "s,^\(\s*db_path\s*:\s*\).*\$,\1$db_path," $VARCONFIG

	# Create data dir & permissions if needed
	if [ ! -d "${RUNCONFDIR}" ]; then
		mkdir -m 0755 -p "${RUNCONFDIR}"
	fi;
}

start_service() {
	setup_syslog
	init_config

	procd_open_instance
	procd_set_param command "$PROG" -c "$VARCONFIG"
	procd_close_instance
}
