#!/sbin/openrc-run
# Calculate system initialization script
# (one-time system configuration on first boot)
# Author: Mir Calculate | License: Apache 2.0
# Copyright (c) 2011-2025 Mir Calculate
# For details, see the LICENSE file or https://www.apache.org/licenses/LICENSE-2

depend() {
	need localmount
	before keymaps consolefont dbus display-manager local
	after access
	use swap hostname udev
	keyword -docker -systemd-nspawn -vserver
}

check_install_ability() {
	FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/var/calculate/distfiles \
		emerge -fq "$1" &>/dev/null
}

is_already_install() {
	local cpv=$1
	local category=${cpv%/*}
	local pkg=${cpv#*/}
	local categoryPath="/var/db/pkg/$category"

	[[ -d "$categoryPath" ]] || return 1
	compgen -G "$categoryPath/$pkg-[0-9]*" >/dev/null
}

install_pkg() {
	local pkg=$1
	ebegin "Installing $pkg"
	FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/var/calculate/distfiles \
		emerge "$pkg" &>/dev/null
	local rc=$?
	eend $rc
	return $rc
}

new_install_pkg() {
	local pkg=$1 mask=$2
	local short=${pkg#*/}

	ebegin "Installing $pkg"
	FETCHCOMMAND=false DISTDIR=/var/calculate/distfiles PKGDIR=/var/calculate/packages \
		/usr/libexec/calculate/cl-video-install "$short" "$mask" &>/dev/null
	local rc=$?
	eend $rc
	return $rc
}

variable_value() {
	/usr/libexec/calculate/cl-variable --value "$1"
}

install_video_driver() {
	einfo "Checking video drivers"
	local drv=""
	local nvidiamask=""
	local rc=0

	case $(variable_value install.os_install_x11_video_drv) in
		nvidia)
			nvidiamask=$(variable_value install.os_nvidia_mask)
			drv="x11-drivers/nvidia-drivers"
			if [[ -n $nvidiamask ]]; then
				mkdir -p /etc/portage/package.mask
				printf '%s\n' "$nvidiamask" >/etc/portage/package.mask/nvidia
			fi
			;;
		*) : ;;
	esac

	if [[ -n $drv ]]; then
		if ! is_already_install "$drv"; then
			if [[ -x /usr/libexec/calculate/cl-video-install ]]; then
				new_install_pkg "$drv" "$nvidiamask" || rc=$?
			else
				if check_install_ability "$drv"; then
					install_pkg "$drv" || rc=$?
				else
					rc=1
				fi
			fi
		fi
	fi
}

# create user guest if system has not non-root user
create_nonroot_user() {
	if command -v cl-desktop &>/dev/null &&
		[[ -z $(variable_value install.cl_migrate_user | sed -r "s/[][,']|root//g") ]] &&
		[[ $(variable_value install.os_install_linux_system) != "server" ]]
	then
		# passwd of non root user
		local nonroot_pw='$5$e/joOLXL$5GfArWgJx7BEcGqil3hTZoPGqWLRUUjCbzvl3gTWN75'
		# name of non root user
		local nonroot_user="guest"

		ebegin "Creating ${nonroot_user} user"
		LANG=C useradd -p "${nonroot_pw}" \
			-G users,wheel,audio,cdrom,video,cdrw,usb,plugdev,games,lp,lpadmin,scanner,uucp \
			"${nonroot_user}"
		chmod 700 "/home/${nonroot_user}"
		eend $?
	fi
}

# create/update root profile
configure_users() {
	if command -v cl-desktop &>/dev/null; then
		LANG=C cl-desktop root
	fi
}

# setup alsautils astate
setup_alsautils() {
	if command -v alsactl &>/dev/null; then
		local alsastatedir=/var/lib/alsa
		local alsahomedir=/var/run/alsasound

		checkpath -q -d -m 0700 -o root:root "${alsahomedir}"
		mkdir -p "${alsastatedir}"

		local vlevel="100%"
		if [[ "$(variable_value install.os_audio)" == "alsa" ]]; then
			vlevel="85%"
		fi

		einfo "Setting up ALSA Mixer Levels"
		# set output volumes to 85% - 100%
		amixer -c 0 scontrols | grep -v Mic | \
			sed -nr "/Wave|Headphone|Master|Front|LFE|Center|Side|Speaker|Surround|PCM/ s/.*'([^']+)'.*/\\1/p" | \
			xargs -I {} amixer -c 0 -q set "{}" "$vlevel" unmute &>/dev/null
		# reduce beep
		amixer -c 0 scontrols | sed -nr "/Beep/ s/.*'([^']+)'.*/\\1/p" | \
			xargs -I {} amixer -c 0 -q set "{}" 10% mute &>/dev/null
		# mute all mics
		amixer -c 0 scontrols | sed -nr "/Mic/ s/.*'([^']+)'.*/\\1/p" | \
			xargs -I {} amixer -c 0 -q set "{}" 0% mute &>/dev/null
		LANG=C alsactl -E HOME="${alsahomedir}" -I -f "${alsastatedir}/asound.state" store
	fi
}

restore_filecaps() {
	if [[ -f /var/lib/calculate/filecaps ]] && command -v filecap &>/dev/null; then
		while IFS= read -r line; do
			[[ -n "$line" ]] && filecap $line
		done < /var/lib/calculate/filecaps
	fi
	rm -f /var/lib/calculate/filecaps
}

start() {
	if rc-update show boot | grep -q " calculate "; then
		local subsystem="$(variable_value main.os_subsystem)"
		local roottype="$(variable_value main.os_root_type)"
		local rootflash="$(variable_value main.os_root_flash_dev)"
		local roottypeext="$(variable_value main.os_root_type_ext)"

		[[ $subsystem == "lxc" ]] && restore_filecaps

		if [[ $roottype != "livecd" ]] || grep -qw "video:nvidia" /proc/cmdline &>/dev/null; then
			install_video_driver
		fi

		setup_alsautils
		LANG=C create_nonroot_user

		if [[ $subsystem == "lxc" ]] || [[ $roottype == "livecd" ]]; then
			LANG=C cl-core --method setup_system --no-progress --usenew-conf --live on --network on
		else
			LANG=C cl-core --method setup_system --no-progress --usenew-conf --live on
		fi

		LANG=C configure_users
		[[ -n $rootflash ]] && mount -o remount,rw "$rootflash"

		if [[ $subsystem != "lxc" ]] && ! [[ -f /var/calculate/server/ca/server.key ]]; then
			cl-core --bootstrap &>/dev/null
		fi

		if [[ $roottype == "livecd" ]]; then
			LANG=C cl-core -u guest
		fi

		if [[ $roottype == "hdd" ]]; then
			cl-core --clear-localuser-cert

			local distdir="/var/calculate/distfiles"
			local pkgdir="/var/calculate/packages"

			local video_script="/usr/local/sbin/cl-video-install"
			local cache_video="/var/cache/calculate/video_drivers"

			[[ -d "${distdir}" ]] && [[ -n "$(ls ${distdir})" ]] && rm "$distdir"/*
			[[ -d "${pkgdir}" ]] && [[ -n "$(ls ${pkgdir})" ]] && rm -r "$pkgdir"/*

			[[ -f "${video_script}" ]] && rm -f -- "${video_script}"
			[[ -f "${cache_video}" ]] && rm -rf -- "${cache_video}"
		fi

		rc-update del calculate boot

		# set en_US sort service order (make net.eth,net.br,net.wlan more preferable than NetworkManager)
		LANG=en_US.utf8 rc-update --update
		udevadm control --reload
		udevadm trigger --action=add --subsystem-match=net
	else
		ewarn "System already configured!"
	fi

	return 0
}
