#!/bin/bash

CLONEZILLA_HOME=$(getent passwd clonezilla|cut -d : -f 6)

#
# First of all, place the SSH configuration for clonezilla and root@proxy
#

mkdir -p ${CLONEZILLA_HOME}/.ssh
#rm -rf ${CLONEZILLA_HOME}/.ssh/*
cp /usr/share/fuss-fucc/clonezilla_live.pub ${CLONEZILLA_HOME}/.ssh/authorized_keys
ssh-keyscan -H proxy > ${CLONEZILLA_HOME}/.ssh/known_hosts 2>/dev/null

# Check if the SSH key already exists, if so check if is in authorized-keys
if [ -e ${CLONEZILLA_HOME}/.ssh/id_rsa.pub ] ; then
	if ! grep $(cat ${CLONEZILLA_HOME}/.ssh/id_rsa.pub|cut -d ' ' -f 2) /root/.ssh/authorized_keys 2>&1 > /dev/null ; then
		echo 'command="if [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^scp[[:space:]]-f ]] || [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^add_client_principal ]] || [[ \"$SSH_ORIGINAL_COMMAND\" =~ rm[[:space:]]/root/ ]]; then $SSH_ORIGINAL_COMMAND; else echo \"Access Denied $SSH_ORIGINAL_COMMAND\"; fi"' $(cat ${CLONEZILLA_HOME}/.ssh/id_rsa.pub) >> /root/.ssh/authorized_keys
	fi
else
	# else, generate a new keypair and send it to root's authorized keys
	ssh-keygen -t rsa -N "" -f ${CLONEZILLA_HOME}/.ssh/id_rsa -C "root@fuss-fucc"
	touch /root/.ssh/authorized_keys
	mv /root/.ssh/authorized_keys /root/.ssh/authorized_keys.old
	grep -v "root@fuss-fucc" /root/.ssh/authorized_keys.old > /root/.ssh/authorized_keys
	echo 'command="if [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^scp[[:space:]]-f ]] || [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^add_client_principal ]] || [[ \"$SSH_ORIGINAL_COMMAND\" =~ rm[[:space:]]/root/ ]]; then $SSH_ORIGINAL_COMMAND; else echo \"Access Denied $SSH_ORIGINAL_COMMAND\"; fi"' $(cat ${CLONEZILLA_HOME}/.ssh/id_rsa.pub) >> /root/.ssh/authorized_keys
fi

chown -R clonezilla. ${CLONEZILLA_HOME}/.ssh
chmod 400 ${CLONEZILLA_HOME}/.ssh/id_rsa*


#
# Then get the SFTP directoty and copy the files
#
#DEBHELPER#

# Source debconf
. /usr/share/debconf/confmodule

# Get the directory
db_get fuss-fucc/sftp_directory
SFTPDIR="$RET"


# Fix the directory in pxelinux
sed -i "s+/srv/clonezilla+$SFTPDIR+g" /srv/tftp/pxelinux.cfg/default


# Copy required files
mkdir -p $SFTPDIR
cp -R /usr/share/fuss-fucc/clonezilla/clientScripts ${SFTPDIR}
test -e ${SFTPDIR}/computerList.txt || cp /usr/share/fuss-fucc/clonezilla/computerList.txt ${SFTPDIR}
cp /usr/share/fuss-fucc/clonezilla/script ${SFTPDIR}

chown -R clonezilla. ${SFTPDIR}/clientScripts
chmod -R 770 ${SFTPDIR}/clientScripts
chown clonezilla. ${SFTPDIR}/computerList.txt
chown clonezilla. ${SFTPDIR}/script
chmod 770 ${SFTPDIR}/script

mkdir -p /etc/fuss-fucc
echo $SFTPDIR > /etc/fuss-fucc/sftpdir
