#!/bin/bash

FAILURE="FAILURE"
SUCCESS="SUCCESS"

if [ -z "$1" ] ; then
  echo "Missing board argument. Exiting."
  exit 1
fi

BOARD=$1
MOUNTPOINT="/tmp/${BOARD}"
INIT_SSH_SERVER="etc/init/openssh-server.conf"
BASHRC="etc/skel/.bashrc"
GIT_CORE="usr/local/libexec/git-core/"
GIT_EXPECTED_EXPORT="export GIT_EXEC_PATH=/usr/local/libexec/git-core"
VIRTUALENV_BIN="usr/local/bin/virtualenv"
CHROMIUM_POLICY="etc/chromium/policies/recommended/nayuos_policy.json"

HAS_FAILED=0

function print_result() {
  test_result=$1
  message=$2

  printf "\t${test_result}: "
  printf "${message}\n"
  if [[ ${test_result} == ${FAILURE} ]] ; then
      HAS_FAILED=1
  fi
}

# MOUNT IMAGE AND GET INFO

install -d "${MOUNTPOINT}"
./mount_gpt_image.sh --safe --most_recent --board ${BOARD} -r ${MOUNTPOINT}
echo $(ls "${MOUNTPOINT}/usr/local")
if [[ $(ls "${MOUNTPOINT}/usr/local") ]] ; then
  opensshd_config=$(ls "${MOUNTPOINT}/${INIT_SSH_SERVER}")
  gitcore=$(ls "${MOUNTPOINT}/${GIT_CORE}")
  gitexport=$(grep "${GIT_EXPECTED_EXPORT}" "${MOUNTPOINT}/${BASHRC}")
  virtualenvbin=$(ls "${MOUNTPOINT}/${VIRTUALENV_BIN}")
  chromium_policy=$(ls "${MOUNTPOINT}/${CHROMIUM_POLICY}")
else
  is_empty=1
fi
./mount_gpt_image.sh --safe --most_recent --board ${BOARD} -r ${MOUNTPOINT} -u
rmdir ${MOUNTPOINT}


# PRINT RESULTS

echo "* test if /usr/local exists"
if [[ "${is_empty}" == "1" ]] ; then
  print_result ${FAILURE} "/usr/local is empty."
else
  print_result ${SUCCESS} "/usr/local is not empty."

  echo "* test openssh server init script absence"
  if [[ ${opensshd_config} ]] ; then
    print_result ${FAILURE} "opensshd config exists: ${opensshd_config}"
  else
    print_result ${SUCCESS} "opensshd config removed."
  fi

  echo "* test if git core directory is not empty"

  if [[ "${gitcore}" == "" ]] ; then
    print_result ${FAILURE} "No git file in ${MOUNTPOINT}/${GIT_CORE}."
  else
    print_result ${SUCCESS} "git core directory exists and is not empty."
  fi

  echo "* test bashrc changes for git paths quick fix"

  if [[ "${gitexport}" == ""  ]] ; then
    print_result ${FAILURE} "Expected alias for git command not in ${MOUNTPOINT}/${BASHRC}. There should be: ${GIT_EXPECTED_EXPORT}"
  else
    print_result ${SUCCESS} "git alias is correct."
  fi

  echo "* test if virtualenv binary exists"

  if [[ ${virtualenvbin} ]] ; then
    print_result ${SUCCESS} "virtualenv binary exists."
  else
    print_result ${FAILURE} "Expected virtualenv binary not in ${MOUNTPOINT}/${VIRTUALENV_BIN}."
  fi

  echo "* test if Chromium policies are installed"

  if [[ ${chromium_policy} ]] ; then
    print_result ${SUCCESS} "Chromium policies are installed."
  else
    print_result ${FAILURE} "Expected Chromium policies file not in ${MOUNTPOINT}/${CHROMIUM_POLICY}."
  fi
fi

exit ${HAS_FAILED}
