#!/bin/sh

# Load ipmodule variables
. /opt/gira/share/devicestack/ipmodule-vars

case "$1" in
  start)

    echo -n "Restoring shadow from template ... "
    mkdir -p "$(dirname $(readlink /etc/shadow))"
    if [ -f /opt/userdata/shadow ]
    then
      cp /opt/userdata/shadow "$(readlink /etc/shadow)"
      echo -n "from userdata ..."
    else
      cp "${SHADOW_TEMPLATE}" "$(readlink /etc/shadow)"
      echo -n "from system ..."
    fi
    echo "done."

    echo -n "Checking existence of default device user ... "
    if [ -f "${DEFAULT_DEVICE_USER_FILE}" ]
    then
      echo "found."
    else
      echo "not found."
      echo -n "Creating default device user ... "
      mkdir -p "${DEVICE_USER_DIR}"
      if echo -n "x8q+DQfMqM4+77LfeRWer2C0A5B2kZ4A4kIfAVeJvbw=" > "${DEFAULT_DEVICE_USER_FILE}"
      then
        echo "done."
      else
        echo "failed."
      fi
    fi

    echo -n "Checking appconfig.xml ... "
    if [ -f "${APPCONFIG_FILE}" ]
    then
      echo "found."
    else
      echo "not found."
      echo -n "Copying appconfig.xml ... "
      if cp "${APPCONFIG_FILE_TEMPLATE}" "${APPCONFIG_FILE}"
      then
        echo "done."
      else
        echo "failed."
      fi
    fi

    echo -n "Checking devicestackconfig.xml ... "
    if [ -f "${DSCONFIG_FILE}" ]
    then
      echo "found."
    else
      echo "not found."
      echo -n "Copying devicestackconfig.xml ... "
      if cp "${DSCONFIG_FILE_TEMPLATE}" "${DSCONFIG_FILE}"
      then
        echo "done."
      else
        echo "failed."
      fi
    fi

    echo -n "Checking custom channel definitions ... "
    if [ -d "${COSTOM_CHANNEL_DIR}" ]
    then
      echo "found."
    else
      echo "not found."
      echo -n "Copying custom channel definitions ... "
      if cp -a "${COSTOM_CHANNEL_DIR_TEMPLATE}" "${COSTOM_CHANNEL_DIR}"
      then
        echo "done."
      else
        echo "failed."
      fi
    fi

    echo -n "Checking custom project definitions ... "
    if [ -d "${CUSTOM_PROJECT_DEFINITION_DIR}" ]
    then
        echo "found."
    else
        echo "not found."
        echo -n "Copying custom project definitions ... "
        if cp -a "${CUSTOM_PROJECT_DEFINITION_DIR_TEMPLATE}" "${CUSTOM_PROJECT_DEFINITION_DIR}"
        then
            echo "done."
        else
            echo "failed."
        fi
    fi

    ;;
  stop)
    ;;
  *)
    echo "Usage: $0 (start|stop)"
    exit 1
esac

exit 0
