#!/bin/bash

HOST=$(cat /etc/hostname)
SYNCLOUD_CONF_PATH=/etc/syncloud
SYNCLOUD_TOOLS_PATH=/usr/local/bin/syncloud

apt-get -y install ntp ntpdate

# tell beagle flasher to skip /data dir
if [[ ${HOST} = "arm" ]]; then
    sed -i '/^copy_rootfs$/i umount /data || true' /opt/scripts/tools/beaglebone-black-eMMC-flasher.sh
fi

cp -r tools ${SYNCLOUD_TOOLS_PATH}
BOOT_SCRIPT_NAME=${SYNCLOUD_TOOLS_PATH}/boot.sh
rm -rf ${BOOT_SCRIPT_NAME}
cp boot.templ ${BOOT_SCRIPT_NAME}
chmod +x ${BOOT_SCRIPT_NAME}
mkdir ${SYNCLOUD_CONF_PATH}
cp version ${SYNCLOUD_CONF_PATH}

# create data folder
DATADIR=/data
mkdir ${DATADIR}

# command: mount hdd to DATADIR
CMD_MOUNTHDD="python $SYNCLOUD_TOOLS_PATH/mounthdd.py $DATADIR"

# add mounting DATADIR script to boot script
echo "$CMD_MOUNTHDD" >> ${BOOT_SCRIPT_NAME}

# command: set permissions for www user to DATADIR
CMD_WWWDATAFOLDER="$SYNCLOUD_TOOLS_PATH/wwwdatafolder.sh $DATADIR"

# add DATADIR permissions script boot script
echo "$CMD_WWWDATAFOLDER" >> ${BOOT_SCRIPT_NAME}

#must be after more critical boot steps
echo "ntpdate -u pool.ntp.org || true" >> ${BOOT_SCRIPT_NAME}

# mount and set permissions to data folder
${CMD_MOUNTHDD}
${CMD_WWWDATAFOLDER}

# add boot script to rc.local
sed -i '/# By default this script does nothing./a '${BOOT_SCRIPT_NAME} /etc/rc.local