#!/usr/bin/env bash
winezgui-identity-remove()
{
  HEADER="$(basename ${0}): ${FUNCNAME[0]}"
  dbug "I: $(basename ${0}): Launched ${FUNCNAME[0]}"
    
  SOURCE "script-check-variables-loaded-or-not"
  script-check-variables-loaded-or-not

  if [ -z "${1}" ]; then
        echo "E: ${HEADER}: Must provide Prefix or Template Directory to process"
        return 1
  else
        DIRECTORY="${1}"
        DIRNAME=$(basename "${1}")
  fi      
  
  SOURCE "winezgui-fetch-replacement-data"
  winezgui-fetch-replacement-data
  
  SOURCE "winezgui-fetch-replacement-files"
  winezgui-fetch-replacement-files "${DIRECTORY}"

  cd "${DIRECTORY}"  
  dbug "I: ${HEADER}: Processing files inside ${DIRNAME}"

  SAVEIFS=${IFS}
  IFS=$(echo -en "\n\b") # needed for sed to work with files in variable
  
  # Do search and replace in the files inside given directory
  for (( i=0; i <${LEN}; i++ )); do
      echo -n "."
      sed "s/${SEARCH[$i]}/${REPLACE[$i]}/g; t;" -i ${FILE_LIST} 2>/dev/null || \
      echo "E: ${HEADER}: Failed to Replace: ${SEARCH[$i]} => ${REPLACE[$i]}" \
      && (echo "\"${SEARCH[i]}\"   ;  \"${REPLACE[i]}\""|column -t -s ";")
  done
  echo " "
  IFS=${SAVEIFS}
  # Rename Directory for Backup
  DSOURCE="${DIRECTORY}/drive_c/users/${USER}"
  DTARGET="${DIRECTORY}/drive_c/users/XOUSERXO"
  # Make sure that directory for the user exists, before moving
  if [ -d "${DIRECTORY}/drive_c/users/${USER}" ]; then
       mv "${DSOURCE}" "${DTARGET}" && \
       dbug "I: ${HEADER}: Renamed ${DSOURCE}"
       dbug "I: ${HEADER}: to      ${DTARGET}"
  fi


  # Remove H: links on Backup
  rm  "${DIRECTORY}/dosdevices/h:" && \
  dbug "I: ${HEADER}: Removed H: symlink ${DIRNAME}/dosdevices/h:"


   # Values->XO? ; If XOUSERHOMEXO not found then backup_function failed
  if [ -f "${1}/Info.yml" ] && \
     (! grep -o "XOUSERHOMEXO" ${INFOFILE} 1>/dev/null 2>/dev/null);
      then
      echo "E:------------------------------------------"
      echo "E: ${FUNCNAME[0]}: Identiy Not Removed for ${USER}!"
      echo "E:------------------------------------------"
      ${ZENITY_CMD} --error --title "Backup Process XOUSERHOMEXO failed" \
                 --text "${USER} Identity is not removed, not ok for sharing!"
  fi
  # Check if identity is removed
  if [ -f "${1}/Info.yml" ] && \
     ( grep -o "XOUSERHOMEXO" ${1}/Info.yml 1>/dev/null 2>/dev/null ); then
       dbug "I: ${FUNCNAME[0]}: Identity removed ${USER}!"
  fi

  # Cleanup variables 
  unset LEN SSSSSSS SEARCH REPLACE FIND_EXE_PATH FPNAME 
  unset WEXE WVER FILE_LIST DTARGET DSOURCE

#   # Find other files which has username in it.
#   SOURCE "winezgui-identity-remove-from-drive-c-files"
#   winezgui-identity-remove-from-drive-c-files "${1}"
}
