#!/bin/bash

## There is more to this script but use this version for now.
## When you get to starting services at boot, there will be 
## a new version of this script.

FSTAB_FILE="/root/fstab"
LOG_FILE="/tmp/onboot.log"
LED_LOADING="/root/onboot.loading.led"
LED_LOADING_ERRORS="/root/onboot.loading.errors.led"
LED_LOADED="/root/onboot.loaded.led"
LED_ERRORS="/root/onboot.errors.led"
error_state=false
rm -f "${LOG_FILE}"
touch "${LOG_FILE}"
./doled.sh "${LED_LOADING}" &

function doLog {
  echo "${1}"
  echo "$(date) > ${1}" >> "${LOG_FILE}"
}

doLog "Starting OnBoot sequence..."

if [[ ! -f ${FSTAB_FILE} ]]; then
  ./doled.sh "${LED_ERRORS}"
  ./doled.sh "${LED_LOADING}" remove
  doLog "${FSTAB_FILE} does not exist! Exiting..."
  exit 1
fi

doLog "Loading ${FSTAB_FILE}..."

while read -r fs mountpoint fstype opts dump pass; do

  [[ "${fs}" =~ ^#.*$ || -z "${fs}" ]] && continue

  if [ ! -d "${mountpoint}" ]; then
    doLog "Creating mountpoint: ${mountpoint}"
    mkdir -p "${mountpoint}"
  fi

  doLog "Mounting ${fs} on ${mountpoint} (type=${fstype}, opts=${opts})"

  mount -t "${fstype}" -o "${opts}" "${fs}" "${mountpoint}" || {
    ./doled.sh "${LED_LOADING_ERRORS}"
    doLog "Failed to mount ${fs} on ${mountpoint}"
    ./doled.sh "${LED_LOADING}" remove
    error_state=true
  }

done < "${FSTAB_FILE}"