#!/sbin/openrc-run

name="opencloud"
description="OpenCloud - file-sync and share server (single-binary runtime)"

: "${opencloud_user:=opencloud}"
: "${opencloud_group:=opencloud}"
: "${opencloud_config_dir:=/etc/opencloud}"
: "${opencloud_data_dir:=/var/lib/opencloud}"
: "${opencloud_logfile:=/var/log/opencloud/opencloud.log}"
: "${opencloud_insecure:=true}"

command="/usr/bin/opencloud"
command_args="server"
command_user="${opencloud_user}:${opencloud_group}"
pidfile="/run/${RC_SVCNAME}.pid"

supervisor="supervise-daemon"
output_log="${opencloud_logfile}"
error_log="${opencloud_logfile}"

export OC_CONFIG_DIR="${opencloud_config_dir}"
export OC_BASE_DATA_PATH="${opencloud_data_dir}"
[ -n "${opencloud_url}" ]        && export OC_URL="${opencloud_url}"
[ -n "${opencloud_log_level}" ]  && export OC_LOG_LEVEL="${opencloud_log_level}"
[ -n "${opencloud_http_addr}" ]  && export PROXY_HTTP_ADDR="${opencloud_http_addr}"
[ -n "${opencloud_tls}" ]        && export PROXY_TLS="${opencloud_tls}"

depend() {
	need net
	use dns logger
	after firewall
}

start_pre() {
	checkpath -d -m 0700 -o "${opencloud_user}:${opencloud_group}" "${opencloud_config_dir}"
	checkpath -d -m 0700 -o "${opencloud_user}:${opencloud_group}" "${opencloud_data_dir}"
	checkpath -d -m 0755 -o "${opencloud_user}:${opencloud_group}" "${opencloud_logfile%/*}"

	if [ ! -f "${opencloud_config_dir}/opencloud.yaml" ]; then
		einfo "No configuration found - initialising OpenCloud in ${opencloud_config_dir}"
		su -s /bin/sh "${opencloud_user}" -c "
			export OC_CONFIG_DIR='${opencloud_config_dir}'
			export OC_BASE_DATA_PATH='${opencloud_data_dir}'
			${opencloud_admin_password:+export IDM_ADMIN_PASSWORD='${opencloud_admin_password}'}
			exec '${command}' init --insecure '${opencloud_insecure}'
		" || return 1
		if [ -z "${opencloud_admin_password}" ]; then
			ewarn "A random admin password was generated."
			ewarn "Find it in ${opencloud_config_dir}/opencloud.yaml (idm.service_user_passwords.admin_password)."
		fi
	fi
}
