#!/bin/sh

. ./config.sh
if [ "${CHAIN}" = "Y" ]; then
    printf "\033[1;36m1.kernel.sh\033[0m\n"
fi

export __MAKE_CONF=${START_PATH}/myfiles/conf/make.conf 

echo "Copying ${KERNEL_FILE} configuration file in /usr/src/sys/i386/conf"
if [ "$RELEASE" = "5" ]; then
  #Copying loader.conf 
  cp /boot/defaults/loader.conf ${JAIL_DIR}/boot/defaults/
  touch ${JAIL_DIR}/boot/loader.conf
  cp ./myfiles/conf/${KERNEL_FILE}.5 /usr/src/sys/i386/conf/${KERNEL_FILE}
  cp /usr/src/sys/i386/conf/GENERIC.hints ${JAIL_DIR}/boot/device.hints
else
  #cp ./myfiles/conf/MINIBSD /usr/src/sys/i386/conf/
  cp ./myfiles/conf/${KERNEL_FILE} /usr/src/sys/i386/conf/
fi


ANSWER="N"
if [ ! "${CHAIN}" = "Y" ]; then
  echo -n "Do you want to edit the kernel file? [N]: "
  read ANSWER
fi
if [ "${ANSWER}" = "Y" -o "${ANSWER}" = "y" ]; then
	${EDITOR} /usr/src/sys/i386/conf/${KERNEL_FILE}
fi 

#ONLY for 4.x kernel
if [ "${RELEASE}" = "4" ]; then
  ANSWER=""
  echo "Do you want to add kernel features"
  echo -n "answering to simple questions [N]? "
  read ANSWER
  if [ "${ANSWER}" = "Y" -o "${ANSWER}" = "y" ]; then
    sh 9.custom_kernel.sh
  fi
fi

echo -n "Building kernel..." && /usr/bin/tput ch 54
if [ "${NOCLEAN}" = "yes" ]; then
    cd /usr/src && make kernel DESTDIR=${JAIL_DIR} -DNOCLEAN
else
    if [ "${KERNEL_SILENT}" = "Y" ]; then
    	cd /usr/src && make kernel KERNCONF=${KERNEL_FILE} DESTDIR=${JAIL_DIR} > /dev/null 2>&1
    else
    	cd /usr/src && make kernel KERNCONF=${KERNEL_FILE} DESTDIR=${JAIL_DIR}
    fi
fi
printf "\033[1;36m[OK]\033[0m\n"

#Removing old kernel
if [ "${RELEASE}" = "5" ]; then
    rm -rf ${JAIL_DIR}/boot/kernel.old
else
    rm -rf ${JAIL_DIR}/modules.old
fi
rm -rf ${JAIL_DIR}/boot/loader.old

cd ${START_PATH}
if [ "${CHAIN}" = "Y" ]; then
    sh 2.libs_devs.sh
fi

