#!/bin/sh

me="[S13restoretemplates]"
# This file has priority over the ordinary template and is used
# for the developer-only packages to override the password
PRIO_SHADOW_TEMPLATE=/opt/userdata/devicestack/shadow.template

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

#$1 template file
#$2 result file
copy_template()
{
  TEMPLATE_FILE=$1
  RESULT_FILE=$2
  
  echo -n "${me} Checking ${RESULT_FILE} ... "
  if [ -f "${RESULT_FILE}" ] || [ -d "${RESULT_FILE}" ]; then
      echo "found."
  else
    echo "not found."
    echo -n "${me} Copying ${TEMPLATE_FILE} ... "
    if cp -a  "${TEMPLATE_FILE}" "${RESULT_FILE}"; then
      echo "done."
    else
       echo "failed."
    fi
  fi
}


case "$1" in
  start)
    echo -n "${me} Restoring shadow from template ... "
    mkdir -p "$(dirname $(readlink /etc/shadow))"
    if [ -f "${PRIO_SHADOW_TEMPLATE}" ]
    then
      install -m 600 "${PRIO_SHADOW_TEMPLATE}" "$(readlink /etc/shadow)"
      echo -n "from userdata ..."
    else
      install -m 600 "${SHADOW_TEMPLATE}" "$(readlink /etc/shadow)"
      echo -n "from system ..."
    fi
    echo "done."

    echo -n "${me} Checking existence of default device user ... "
    if [ -f "${DEFAULT_DEVICE_USER_FILE}" ]
    then
      echo "found."
    else
      echo "not found."
      mkdir -p "${DEVICE_USER_DIR}"

      # If device has initial device password
      if [ -f /opt/extparam/fddp ]
      then
        echo -n "${me} Creating device user with initial device password..."
        install -m 600 /dev/null "${DEFAULT_DEVICE_USER_FILE}"
        echo -n "pwd:" > "${DEFAULT_DEVICE_USER_FILE}"
        IGPW=$(cat /opt/extparam/fddp)
        if /opt/gira/bin/encode-pw.sh "${IGPW}" >> "${DEFAULT_DEVICE_USER_FILE}"
        then
          echo "done."
        else
          echo "failed."
        fi
      else
        echo -n "${me} Creating default device user ... "
        if echo -n "x8q+DQfMqM4+77LfeRWer2C0A5B2kZ4A4kIfAVeJvbw=" > "${DEFAULT_DEVICE_USER_FILE}"
        then
          echo "done."
        else
          echo "failed."
        fi
      fi
    fi
    copy_template ${APPCONFIG_FILE_TEMPLATE} ${APPCONFIG_FILE}    
    copy_template ${DSCONFIG_FILE_TEMPLATE} ${DSCONFIG_FILE}
    copy_template ${COSTOM_CHANNEL_DIR_TEMPLATE} ${COSTOM_CHANNEL_DIR}
    copy_template ${CUSTOM_PROJECT_DEFINITION_DIR_TEMPLATE} ${CUSTOM_PROJECT_DEFINITION_DIR}
    copy_template ${OPENVPN_TEMPLATE_DIR} ${OPENVPN_CONFIG_DIR}    

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

exit 0
