#!/bin/bash

function create_dir {
	if [[ -d "$1" && ! -L "$1" ]] ; then
    echo "$1 already exists!"
else 
	echo "$1 does not exists! Creating..."
    mkdir $1
fi
chmod 777 $1
}

function copy_file {
	if cp -r $1 $2; then
		echo "Copying $2"
	else
		echo -e "\033[0;31mCopy failed! Exiting...\033[0m" 1>&2
		exit 1
	fi
}


# START

if [[ $EUID -ne 0 ]]; then
   echo -e "\033[0;31mThis script must be run as root!\033[0m" 1>&2
   exit 1
fi

if [[ $1 =~ ^N[0-9]{3}$ ]] ; then
	if [[ -d "/home/SYSNODE" && ! -L "/home/SYSNODE" ]] ; then
		echo -e "\033[0;31mNode already installed! Exiting...\033[0m"
		exit 1
	else
		echo "Installing node $1..."
	fi
else 
	echo -e "\033[0;31mIncorrect node name! Exiting...\033[0m" 1>&2
	exit 1
fi

ret=false
getent passwd chn21 >/dev/null 2>&1 && ret=true

if $ret; then
    echo "User chn21 already exists!"
else
    echo "User chn21 does not exist! Creating..."
    useradd -m chn21
fi

ret=false
getent passwd chn22 >/dev/null 2>&1 && ret=true

if $ret; then
    echo "User chn22 already exists!"
else
    echo "User chn22 does not exist! Creating..."
    useradd -m chn22
fi

echo "Creating directory tree..."

create_dir /home/D1
create_dir /home/D2
create_dir /mnt/tmp
create_dir /home/SYSNODE

echo "Copying executables and configs..."

# loopU
copy_file bin/loopU/loopU /home/chn21/loopU
copy_file bin/loopU/uloopd /home/chn21/uloopd
copy_file bin/loopU/run /home/chn21/run

# loopR
copy_file bin/loopR/loopR /home/chn22/loopR 
copy_file bin/loopR/rloopd /home/chn22/rloopd
copy_file bin/loopR/run /home/chn22/run

# serverS
copy_file bin/mserverS /home/SYSNODE/mserverS
copy_file bin/runserverS /home/SYSNODE/runserverS
echo -ne $1 > /home/SYSNODE/SERVER_ID

# main-loop
copy_file bin/mloopN /home/SYSNODE/mloopN
copy_file bin/mountRAM /home/SYSNODE/mountRAM
copy_file bin/md5m /home/SYSNODE/md5m
copy_file bin/mk_image /home/SYSNODE/mk_image
copy_file bin/regen /home/SYSNODE/regen

# clientN
copy_file bin/clientNR /home/SYSNODE/clientNR
copy_file bin/clientNW /home/SYSNODE/clientNW
copy_file bin/from-buffer-to-node /home/SYSNODE/from-buffer-to-node
copy_file bin/from-node-to-buffer /home/SYSNODE/from-node-to-buffer
copy_file bin/MD-from-buffer-to-node /home/SYSNODE/MD-from-buffer-to-node
copy_file bin/MD-from-node-to-buffer /home/SYSNODE/MD-from-node-to-buffer
copy_file bin/READ-ROBR /home/SYSNODE/READ-ROBR
copy_file bin/READ-ROBU /home/SYSNODE/READ-ROBU
copy_file bin/run_read /home/SYSNODE/run_read
copy_file bin/run_readMD /home/SYSNODE/run_readMD
copy_file bin/run_read_robR /home/SYSNODE/run_read_robR
copy_file bin/run_read_robU /home/SYSNODE/run_read_robU
copy_file bin/run_write /home/SYSNODE/run_write
copy_file bin/run_writeMD /home/SYSNODE/run_writeMD

echo "Registering startup scripts..."

# register statrup script
copy_file bin/mloopNd /etc/init.d/mloopNd
chkconfig --add mloopNd
chkconfig --level 35 mloopNd on

echo -e "\033[0;32m$1 installation Complete!\033[0m"




