#!/usr/bin/env cbsd
#v10.0.2
CBSDMODULE="jail"
CIXARG="jname type mode file"
CIXOPTARG=""
MYDESC="Import or export from/to ascii rctl.conf from/to SQLite3 tables for jail"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

Import or export from/to ascii rctl.conf from/to SQLite3 tables for jail.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}type=${N0_COLOR}  - rctl or extra;
 ${N2_COLOR}mode=${N0_COLOR}  - tosql or tofile;
 ${N2_COLOR}file=${N0_COLOR}  - ascii file;

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd jmkrctlconf jname=myjail type=rctl mode=tosql file=/path/to/rctl.conf
 # cbsd jmkrctlconf jname=myjail type=extra mode=tofile file=/path/to/extra.conf

${H3_COLOR}See also${N0_COLOR}:

  cbsd jrctl --help
  cbsd jrctl-tui --help

"

. ${subrdir}/nc.subr
. ${distsharedir}/rctl.conf
. ${subrdir}/jrctl.subr
. ${strings}
. ${tools}

cixinit

header() {
${CAT_CMD} >${file} <<EOF
# DO NOT EDIT THIS FILE. PLEASE USE INSTEAD:
# cbsd jrctl-tui jname=${jname}
EOF
}

tofile()
{
	${TRUNCATE_CMD} -s0 ${file}

	case "${type}" in
		"rctl")
			header
			for i in ${RCTL}; do
				capture VAL cbsdsqlro local "SELECT ${i} FROM rctl WHERE jname='${jname}'"
				[ "${VAL}" = "(null)" -o -z "${VAL}" -o "${VAL}" = "0" ] && continue
				case "${i}" in
					readbps|writebps|readiops|writeiops)
						echo "${i}:throttle=${VAL}" > ${file}
					;;
					*)
						echo "${i}:deny=${VAL}" > ${file}
					;;
				esac
			done
			;;
		"extra")
			header
			for i in ${RCTL_EXTRA}; do
				capture VAL cbsdsqlro local "SELECT ${i} FROM rctl WHERE jname='${jname}'"
				[ "${VAL}" = "(null)" -o -z "${VAL}" -o "${VAL}" = "0" ] && continue
				echo "${i}=${VAL}" > ${file}
			done
			;;
		*)
			err 1 "${N1_COLOR}type= must be 'rctl' or 'extra'${N0_COLOR}"
			;;
	esac
}

tosql()
{
	local _myval _items _res
	_num=0

	[ ! -f "${file}" ] && err 1 "${N1_COLOR}No such file: ${N2_COLOR}${file}${N0_COLOR}"

	case "${type}" in
		"rctl")
			capture _tr_out ${TR_CMD} ":=" " " < ${file}
			capture _awk_out ${AWK_CMD} -F " " '{printf("%s=\"%s\"\n", $1,$3); }' <<< "${_tr_out}"
			eval "${_awk_out}"
			;;
		"extra")
			capture _cfg ${CAT_CMD} ${file}
			eval "${_cfg}"
			;;
	esac

	capture _res cbsdsqlro local "SELECT jname FROM rctl WHERE jname='${jname}'"
	[ -z "${_res}" ] && cbsdsqlrw local "INSERT INTO rctl ( jname ) VALUES ( '${jname}' )"

	case "${type}" in
		"rctl")
			for _items in ${RCTL}; do
				eval _myval=\$${_items}
				[ -z "${_myval}" ] && _myval="0"
				cbsdsqlrw local "UPDATE rctl SET ${_items}='${_myval}' WHERE jname='${jname}'"
			done
			;;
		"extra")
			for _items in ${RCTL_EXTRA}; do
				eval _myval=\$${_items}
				[ -z "${_myval}"  ] && _myval="0"
				cbsdsqlrw local "UPDATE rctl SET ${_items}='${_myval}' WHERE jname='${jname}'"
			done
			;;
	esac
}

# MAIN
case "${mode}" in
	"tofile")
		tofile
		;;
	"tosql")
		tosql
		;;
	*)
		err 1 "${N1_COLOR}mode= must be 'tosql' or 'tofile'${N0_COLOR}"
		;;
esac

# exit code 0 is nessesary for dot()
exit 0
