#!/bin/ksh93

typeset -r VERSION='1.0' FPROG=${.sh.file} PROG=${FPROG##*/} SDIR=${FPROG%/*}

unset DEFAULTS; typeset -r DEFAULTS=(
	[CFG]='/etc/grafana/grafana.ini'
	[PDIR]='/etc/grafana/provisioning'
	[GRP]='daemon'
)

USAGE="[-?${VERSION}"' ]
[-copyright?Copyright (c) 2020 Jens Elkner. All rights reserved.]
[-license?CDDL 1.0]
[+NAME?'"${PROG}"' - pre-configure grafana.]
[+DESCRIPTION?Check whether required grafana config files exist. If not, default sample/config files get installed to the related pathes.]
[h:help?Show this help and exit.]
[F:functions?Show a list of all functions defined within this script.]
[T:trace]:[functionList?A comma separated list of the names of functions to trace during execution.]
[+?]
[c:config]:[file?The grafana config file. Default: '"${DEFAULTS[CFG]}"']
[g:group]:[gid?Make any copied file readable by group \agid\a. Default: '"${DEFAULTS[GRP]}"']
[p:pconfig]:[path?The grafana provisioning config directory. Default: The provisioning subdirectory of the directory containing the config file.]
[n:dry?Just show, what would be done, but do not do it.]
'

function showUsage {
    [[ -n $1 ]] && X='-?' ||  X='--man'
    getopts -a ${PROG} "${ print ${USAGE} ; }" OPT $X
}

# copy $SRC to $DST if $DST does not yet exist and create dirs as needed.
function cpFile {
	typeset SRC="$1" DST="$2" GRP=$3 D
	[[ -e ${DST} ]] && return 1
	[[ -e ${SRC} ]] || return 2
	D=${DST%/*}
	if [[ ! -d $D ]]; then
		${DRY} mkdir -p "$D" || return 3
		${DRY} chmod g+r "$D"
		${DRY} chgrp ${GRP} "$D"
	fi
	${DRY} cp ${SRC} ${DST} || return 4
	${DRY} chmod g+r ${DST}
	${DRY} chgrp ${GRP} ${DST}
}

function doMain {
	typeset X BASEDIR='/usr/share/grafana/conf' K E V R
	integer E=0

	[[ -z ${OPT[CFG]} ]] && OPT[CFG]=${DEFAULTS[CFG]}
	# copy default.ini
	cpFile ${BASEDIR}/sample.ini ${OPT[CFG]} ${OPT[GRP]}
	E=$?
	if (( E == 1 )); then
		E=0
	elif (( E == 0 )); then
		X=${ realpath ${OPT[CFG]}; }
		X=${X%/*}
		[[ -z ${OPT[PDIR]} ]] && OPT[PDIR]="$X/provisioning"
		if [[ $X != ${OPT[CFG]%/*} ]]; then
			# we leave logdir as is
			${DRY} sed -i -e "/^; *data *=/ s|^.*|data = $X/data|" \
				-e "/^; *plugins *=/ s|^.*|data = $X/plugins|" \
				-e "/^; *provisioning *=/ s|^.*|provisioning = ${OPT[PDIR]}|" \
				${OPT[CFG]}
		fi
		# new copy of sample.ini: /etc/grafana/ldap.toml is an entry in it
		cpFile ${BASEDIR}/ldap.toml /etc/grafana/ldap.toml ${OPT[GRP]}
	fi
	if [[ -z ${OPT[PDIR]} && -e ${OPT[CFG]} ]]; then
		while read K E V R ; do
			[[ $K == 'provisioning' && $E == '=' ]] && OPT[PDIR]="$V" && break
		done<${OPT[CFG]}
	fi

	if [[ -z ${OPT[PDIR]} ]]; then
		[[ -z $X ]] && X=${ realpath ${OPT[CFG]}; } && X=${X%/*}
		OPT[PDIR]="$X/provisioning"
	fi

	BASEDIR+='/provisioning'
	cpFile /dev/null ${OPT[PDIR]}/README ${OPT[GRP]}	# ignore fake
	for X in access-control alerting dashboards datasources notifiers plugins
	do
		# We name it not *.yaml so that one can see, that they are not enabled
		# by default - they are basically files with comments, only anyway.
		# So ppl have an easy way to complement their setup w/o touching the
		# originals distributed (and removed/overwritten) with the package.
		cpFile ${BASEDIR}/$X/sample.yaml ${OPT[PDIR]}/$X/sample.yam ${OPT[GRP]}
		(( $? > 1 )) && (( E++ ))
	done

	return $E
}

unset DRY OPT ; DRY= X="${ print ${USAGE} ; }"
typeset -A OPT
while getopts "${X}" option ; do
    case "${option}" in
        F) typeset +f ; exit 0 ;;
        T)  if [[ ${OPTARG} == 'ALL' ]]; then
                typeset -ft ${ typeset +f ; }   
                set -x
            else
                typeset -ft ${OPTARG//,/ }
            fi
            ;;
        h) showUsage ; exit 0 ;;
		c) OPT[CFG]=${OPTARG} ;;
		g) OPT[GRP]=${OPTARG} ;;
		p) OPT[PDIR]=${OPTARG} ;;
        n) DRY='print --' ;;
    esac
done
IDX=$(($OPTIND-1))
shift $IDX
unset X IDX

doMain "$@" || exit 255
