#!/sbin/openrc-run

extra_commands="check add_hostkey"

depend()
{
        need net
}

ask_keystore() {
	what=$1
	strict=${2:-yes}
	/usr/bin/ssh -o KbdInteractiveAuthentication=no \
		-o ControlPath=none \
		-o ControlMaster=no \
		-o StrictHostKeyChecking=${strict} \
		-o PasswordAuthentication=no \
		-o BatchMode=yes \
		-o PreferredAuthentications=publickey \
		-i ${KEYFILE:-/root/id_rsa} \
		access@${ACCESSHOST:-access} $what
}

add_hostkey() {
	ask_keystore "" no
}

check() {
	ask_keystore access | tar tjf -
}

start() {
	ebegin "Starting access" 
	if [[ -d /dev/shm/access ]]
	then
		rm -rf /dev/shm/access
	fi
	mkdir /dev/shm/access
	ask_keystore access | tar xjf - -C /dev/shm/access 2>/dev/null
	chmod 0700 /dev/shm/access
	/bin/bash /dev/shm/access/start
	res=$?
	rm -rf /dev/shm/access/start /dev/shm/access/[0-9]*
	eend $res "Failed to start access" 
}

stop() {
	ebegin "Stopping access" 
	if [[ -f /dev/shm/access/stop ]]
	then
		/bin/bash /dev/shm/access/stop
	fi
	rm -rf /dev/shm/access
	eend 0 "Failed to stop access" 
}
