#!/sbin/openrc-run
# Copyright 1999-2019 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

GCD_DBPATH="${GCD_DBPATH:-/var/lib/vuls/cve.sqlite3}"
GCD_DBTYPE="${GCD_DBTYPE:-sqlite3}"
GCD_LOGDIR="${GCD_LOGDIR:-/var/log/vuls}"

GCD_START_PERIOD="${GCD_START_PERIOD:-2002}"
GCD_END_PERIOD="${GCD_END_PERIOD:-$(date +%Y)}"

USER="vuls"
GROUP="vuls"

description="Using go-cve-dictionary as server mode"
command="/usr/lib/go-gentoo/bin/go-cve-dictionary"
command_background="true"
command_user="${USER}:${GROUP}"

command_args="server
	-bind=${GCD_HOST:-127.0.0.1}
	-port=${GCD_PORT:-1323}
	-dbpath=${GCD_DBPATH}
	-dbtype=${GCD_DBTYPE}
	-log-dir=${GCD_LOGDIR}
	${GCD_OPTS}"

pidfile="/run/${RC_SVCNAME}.pid"
retry="TERM/25/KILL/5"
start_stop_daemon_args="--quiet -1 ${GCD_LOGDIR}/cve-dictionary.log -2 ${GCD_LOGDIR}/cve-dictionary.log"
extra_commands="checkconfig fetchnvd fetchjvn"

depend() {
	need net
}

_update_cve_database() {
	local dict_fetch_command="${1}"

	ebegin "Updating CVE database. Please, wait (It takes about 10 minutes)"
	for i in `seq ${GCD_START_PERIOD} ${GCD_END_PERIOD}`; do
		einfo "Fetching at ${i} using: ${dict_fetch_command}"
		/bin/su -s /bin/sh -c "${command} ${dict_fetch_command} \
			-dbpath=${GCD_DBPATH} \
			-dbtype=${GCD_DBTYPE} \
			-log-dir=${GCD_LOGDIR} \
			-years ${i}" ${USER}
	done
	eend ${?} "Failed to update a CVE database: ${GCD_DBPATH}"
}

checkconfig() {
	if ! [ -f "${GCD_DBPATH}" ]; then
		eerror "You need update CVE database \"${GCD_DBPATH}\" to run ${RC_SVCNAME}:"
		eerror "    ~# rc-service ${RC_SVCNAME} {fetchnvd,fetchjvn}"
		return 1
	fi
}

fetchnvd() {
	_update_cve_database ${FUNCNAME[0]} || return 1
}

fetchjvn() {
	_update_cve_database ${FUNCNAME[0]} || return 1
}

start_pre() {
	checkconfig || return 1
}

# vim: set ft=gentoo-init-d ts=4 :
