#!/bin/bash


################################################################################
# Variables                                                                    #
################################################################################
DMS_LOG="/mnt/persistent-data/evtec-ecp-data/log/DMS.log"  # device maintenance server
IPK_ENDING="ipk"
PATH_OPKG_FOLDER="/opt/opkg-persistent"
PATH_OPKG_STATUS_FILE="$PATH_OPKG_FOLDER/status"
ECP_SERVICES=(ServiceSupervisor CMDisplay AndchargeDisplay ConfigMigration DCMSControl ECP HmiControl MSIControl MeterControl PowerSinkControl StorageControl VehicleControl)
UPLOAD_PATH="/mnt/persistent-data/uploads/packages/"
VALID_DESCRIPTION_INFO="Description:"



################################################################################
# Functions                                                                    #
################################################################################
function log_info () {
  echo "$(date +%Y-%m-%d\ %H:%M:%S): $1 " >> "${DMS_LOG}"
}

function get_file_paths() {
  local ending="$1"
  find "${UPLOAD_PATH}" -name "*.${ending}" -type f | while IFS= read -r file; do
    if [[ -n "$file" ]]; then
      # remove whitespaces and save anew
      new_file=$(echo "$file" | tr -d '[:space:]')
      if [[ "$file" != "$new_file" ]]; then
        mv "$file" "$new_file"
      fi
      echo "$new_file"
    fi
  done
}

function install_packages () {
  local file_paths="$1"  # first argument shall be a list of file paths previously explored
  if [[ -z "${file_paths}" ]]; then
    log_info "There are no packages found to be installed."
  else
    # Stop all possible running ECP services before the installation starts
    for service in "${ECP_SERVICES[@]}"; do
      if systemctl is-active --quiet "$service"; then
        echo "Stopping $service..."
        systemctl stop "$service"
      fi
    done

    for file in ${file_paths}; do  # Does not work with spaces in names
      log_info "Accessing ${file} ..."
      # check file ending and check for valid package info
      if [[ "${file: -3}" == "${IPK_ENDING}" ]] && opkg info "${file}" | grep "${VALID_DESCRIPTION_INFO}" >> "${DMS_LOG}" ; then
        log_info "Trying to install package ..."
        if opkg install "${file}" --force-depends >> "${DMS_LOG}" 2>&1 ; then
          log_info "Package has been installed successfully!"
        else
          return_code=$?
          log_info "Installation failed (return code ${return_code})."
          # refusing to install as it matches the installed version
          if [[ "${return_code}" == "255" ]] ; then
            log_info "force reinstalling...."
            opkg install "${file}" --force-reinstall >> "${DMS_LOG}" 2>&1
          fi
        fi
      else
        log_info "Package seems to be corrupted (ending or info)."
      fi
      log_info "removing installation file from uploads folder."
      rm "${file}"
    done
    log_info "Copy status file to persistent path."
    mkdir -p $PATH_OPKG_FOLDER
    cp -f /var/lib/opkg/status $PATH_OPKG_STATUS_FILE

    log_info "Rebooting device."
    systemctl reboot
  fi
}

################################################################################
# Main entry                                                                   #
################################################################################
# Call the function with ipk as file endings to look for and store the result in a variable
install_packages "$(get_file_paths ${IPK_ENDING})"
exit