#!/bin/bash

sys=`uname -s`

[[ -d /theox ]] || sudo mkdir -p /theox/system
[[ -h /system ]] || sudo ln -s /home/system/disks/s /system

echo "Setting owner on files in home"
cd /home/system
sudo chown system:theox *

if [[ "$sys" == "Linux" ]]; then
	echo "Moving spooler"
	[ -f disks/s/theox/spooler/system.spooler/queue ] && sudo mv disks/s/theox/spooler/system.spooler/queue __spooler_queue__
	sudo chown -R system:theox disks/s
else
	chown -R system:theox .
fi

echo "Setting permissions on files"
find disks -type f -exec chmod u+rw,g+r {} +

echo "Setting permissions on executables"
chmod -f 0755 disks/s/theox/bin/* \
	disks/s/theox/command/* \
	disks/s/theox/install/* \
	disks/s/theox/os/* 

if [[ "$sys" == "Linux" ]]; then
	echo "Setting owner on suid executables"
	sudo chown -f root:theox \
		disks/s/theox/bin/change \
		disks/s/theox/bin/copyfile \
		disks/s/theox/bin/create \
		disks/s/theox/bin/erase \
		disks/s/theox/bin/force \
		disks/s/theox/bin/logon \
		disks/s/theox/bin/logoff \
		disks/s/theox/bin/logto \
		disks/s/theox/bin/move \
		disks/s/theox/bin/rename \
		disks/s/theox/bin/spooler \
		disks/s/theox/bin/txgensign \
		disks/s/theox/bin/txsystem \
		disks/s/theox/bin/stop \
		disks/s/theox/os/fileserv \
		disks/s/theox/os/nucleus

	echo "Setting permissions on suid executables"
	sudo chmod -f +s \
		disks/s/theox/bin/change \
		disks/s/theox/bin/copyfile \
		disks/s/theox/bin/create \
		disks/s/theox/bin/erase \
		disks/s/theox/bin/force \
		disks/s/theox/bin/logon \
		disks/s/theox/bin/logoff \
		disks/s/theox/bin/logto \
		disks/s/theox/bin/move \
		disks/s/theox/bin/rename \
		disks/s/theox/bin/spooler \
		disks/s/theox/bin/txgensign \
		disks/s/theox/bin/txsystem \
		disks/s/theox/bin/stop \
		disks/s/theox/os/fileserv \
		disks/s/theox/os/nucleus
	
	echo "Setting owner on theosutils and winutils"
	sudo chown -f system:theox disks/s/theosutils/*
	sudo chown -f system:theox disks/s/winutils/*
	
	echo "Setting owner and permissions on dataserv"
	[[ -f disks/s/theox/os/dataserv ]] && sudo chown root:root disks/s/theox/os/dataserv
	[[ -f disks/s/theox/os/dataserv ]] && sudo chmod +s disks/s/theox/os/dataserv

	if [[ -d __spooler_queue__ ]]; then
		sudo mv __spooler_queue__ disks/s/theox/spooler/system.spooler/queue
		echo "Setting owner on spooler queue"
		sudo chown -f system:theox disks/s/theox/spooler/system.spooler/queue
		echo "Setting group on spooler files"
		sudo chgrp -f theox disks/s/theox/spooler/system.spooler/queue/*
		echo "Setting permissions on spooler files"
		sudo chmod -f 0664 disks/s/theox/spooler/system.spooler/queue/*
	fi
fi

echo "Setting permissions on directories"
find disks -type d -exec chmod 0775 {} \;

if [[ -f /dev/shm/theox-nucleus ]]; then
	sudo chown system:theox /dev/shm/theox-nucleus;
	sudo chmod 0660 /dev/shm/theox-nucleus
fi

[[ -f disks/s/theox/os/myperms ]] && . disks/s/theox/os/myperms

exit 0
