#!/bin/sh
# SecuBox Nextcloud manager

CONFIG="nextcloud"
CONTAINER="secbx-nextcloud"
OPKG_UPDATED=0

usage() {
	cat <<'USAGE'
Usage: nextcloudctl <command>

Commands:
  install         Install prerequisites, prepare directories, pull image
  check           Run prerequisite checks
  update          Pull new image and restart
  status          Show container status
  logs            Show container logs (use -f to follow)
  occ             Run Nextcloud OCC command (e.g., occ config:system:set trusted_domains 1 --value=example.com)
  service-run     Internal: run container via procd
  service-stop    Stop container
USAGE
}

require_root() { [ "$(id -u)" -eq 0 ]; }

uci_get() { uci -q get ${CONFIG}.main.$1; }

defaults() {
	image="$(uci_get image || echo nextcloud:latest)"
	data_path="$(uci_get data_path || echo /srv/nextcloud)"
	port="$(uci_get port || echo 80)"
	admin_user="$(uci_get admin_user || echo admin)"
	admin_password="$(uci_get admin_password)"
	trusted_domains="$(uci_get trusted_domains || echo cloud.local)"
	timezone="$(uci_get timezone || echo UTC)"
}

ensure_dir() { [ -d "$1" ] || mkdir -p "$1"; }

ensure_packages() {
	for pkg in "$@"; do
		if ! opkg status "$pkg" >/dev/null 2>&1; then
			if [ "$OPKG_UPDATED" -eq 0 ]; then
				opkg update || return 1
				OPKG_UPDATED=1
			fi
			opkg install "$pkg" || return 1
		fi
	done
}

check_prereqs() {
	defaults
	ensure_dir "$data_path"
	[ -d /sys/fs/cgroup ] || { echo "[ERROR] /sys/fs/cgroup missing" >&2; return 1; }
	ensure_packages dockerd docker containerd
	/etc/init.d/dockerd enable >/dev/null 2>&1
	/etc/init.d/dockerd start >/dev/null 2>&1
}

pull_image() { defaults; docker pull "$image"; }

stop_container() { docker stop "$CONTAINER" >/dev/null 2>&1 || true; docker rm "$CONTAINER" >/dev/null 2>&1 || true; }

cmd_install() {
	require_root || { echo Root required >&2; exit 1; }
	check_prereqs || exit 1
	ensure_dir "$data_path/html"
	ensure_dir "$data_path/apps"
	ensure_dir "$data_path/config"
	ensure_dir "$data_path/data"
	pull_image || exit 1
	uci set ${CONFIG}.main.enabled='1'
	uci commit ${CONFIG}
	/etc/init.d/nextcloud enable
	echo "Nextcloud prerequisites installed."
	echo "IMPORTANT: Set admin_password in /etc/config/nextcloud before starting"
	echo "Start with: /etc/init.d/nextcloud start"
	echo "Then configure trusted domains with: nextcloudctl occ config:system:set trusted_domains 1 --value=your-domain.com"
}

cmd_check() { check_prereqs; echo "Prerequisite check completed."; }

cmd_update() {
	require_root || { echo Root required >&2; exit 1; }
	pull_image || exit 1
	/etc/init.d/nextcloud restart
}

cmd_status() { docker ps -a --filter "name=$CONTAINER"; }

cmd_logs() { docker logs "$@" "$CONTAINER"; }

cmd_occ() {
	docker exec -u www-data "$CONTAINER" php occ "$@"
}

cmd_service_run() {
	require_root || { echo Root required >&2; exit 1; }
	check_prereqs || exit 1
	defaults
	stop_container

	local docker_args="--name $CONTAINER"
	docker_args="$docker_args -p ${port}:80"
	docker_args="$docker_args -v $data_path/html:/var/www/html"
	docker_args="$docker_args -v $data_path/apps:/var/www/html/custom_apps"
	docker_args="$docker_args -v $data_path/config:/var/www/html/config"
	docker_args="$docker_args -v $data_path/data:/var/www/html/data"
	docker_args="$docker_args -e TZ=$timezone"

	# Set admin credentials if provided
	[ -n "$admin_user" ] && docker_args="$docker_args -e NEXTCLOUD_ADMIN_USER=$admin_user"
	[ -n "$admin_password" ] && docker_args="$docker_args -e NEXTCLOUD_ADMIN_PASSWORD=$admin_password"

	# Set trusted domains
	[ -n "$trusted_domains" ] && docker_args="$docker_args -e NEXTCLOUD_TRUSTED_DOMAINS=$trusted_domains"

	exec docker run --rm $docker_args "$image"
}

cmd_service_stop() { require_root || { echo Root required >&2; exit 1; }; stop_container; }

case "${1:-}" in
	install) shift; cmd_install "$@" ;;
	check) shift; cmd_check "$@" ;;
	update) shift; cmd_update "$@" ;;
	status) shift; cmd_status "$@" ;;
	logs) shift; cmd_logs "$@" ;;
	occ) shift; cmd_occ "$@" ;;
	service-run) shift; cmd_service_run "$@" ;;
	service-stop) shift; cmd_service_stop "$@" ;;
	help|--help|-h|'') usage ;;
	*) echo "Unknown command: $1" >&2; usage >&2; exit 1 ;;
esac
