#!/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
  
  printf "%s Checking %s ... \\n" "${me}" "${RESULT_FILE}"
  if [ -f "${RESULT_FILE}" ] || [ -d "${RESULT_FILE}" ]; then
    printf "found.\\n"
  else
    printf "not found.\\n"
    printf "%s Copying %s ... \\n" "${me}" "${TEMPLATE_FILE}"
    if cp -a  "${TEMPLATE_FILE}" "${RESULT_FILE}"; then
      printf "done.\\n"
    else
      printf "failed.\\n"
    fi
  fi
}

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

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

      # If device has initial device password
      if [ -f /opt/extparam/fddp ]
      then
        printf "%s Creating device user with initial device password...\\n" "${me}"
        install -m 600 /dev/null "${DEFAULT_DEVICE_USER_FILE}"
        printf "pwd:" > "${DEFAULT_DEVICE_USER_FILE}"
        IGPW=$(cat /opt/extparam/fddp)
        if /opt/gira/bin/encode-pw.sh "${IGPW}" >> "${DEFAULT_DEVICE_USER_FILE}"
        then
          printf "done.\\n"
        else
          printf "failed.\\n"
        fi
      else
        printf "%s Creating default device user ... \\n" "${me}"
        if printf "x8q+DQfMqM4+77LfeRWer2C0A5B2kZ4A4kIfAVeJvbw=" > "${DEFAULT_DEVICE_USER_FILE}"
        then
          printf "done.\\n"
        else
          printf "failed.\\n"
        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)
    ;;
  *)
    printf "Usage: %s (start|stop)\\n" "$0"
    exit 1
esac

exit 0
