#!/usr/bin/env bash
# Ask user to select an image icon or exe file to extract icon from
# If No argument is given ask
script-change-icon()
{
  HEADER="$(basename ${0}): ${FUNCNAME[0]}"
  
  SOURCE "script-check-variables-loaded-or-not"
  script-check-variables-loaded-or-not
  dbug "I: $(basename ${0}): Launched ${FUNCNAME[0]}"
  if [ -z "${1}" ]; then
       GET_ICON=$(${ZENITY_CMD}   --file-selection \
                           --file-filter=""*.png" "*.jpg" "*.svg" "*.exe" "*.ico"")
  else
       GET_ICON="${1}"
  fi

  # If user cancels
  if [ -z "${GET_ICON}" ]; then #if no icon is selected
       dbug "I: Script: ${FUNCNAME[0]}: Cancelled!"
       # Return to Game window
       Script_Window
  fi

  # Determine if exe is given to extract icon
  GET_ICON_EXT="${GET_ICON##*.}"

  if [ "${GET_ICON_EXT}" = "exe" ]; then
       dbug "I: Script: ${FUNCNAME[0]}: Exe file selected to extract icon!"
       unset TEMP_DIR
       TEMP_DIR="${WINEZGUIDIR}/tmp"
       # Extract icon and convert it to several png files of diferent quality,
       # Create a temporary Directory to extract icon from the exe file
       dbug "I: Script: ${FUNCNAME[0]}: Extraction from ${GET_ICON}"
       mkdir -p ${TEMP_DIR} && \
       dbug "I: Script: ${FUNCNAME[0]}: Created directory ${TEMP_DIR}"

       # wrestool extracts ico file from EXE
       echo "${WRESTOOL_CMD} -x -t 14 ${GET_ICON} > ${TEMP_DIR}/${EXE_LESS}.ico "
       ${WRESTOOL_CMD} -x -t 14 "${GET_ICON}" > "${TEMP_DIR}/${EXE_LESS}.ico" \
       2> /dev/null && \
       dbug "I: Script: ${FUNCNAME[0]}: Wrestool executed"

       # Only try to extract Icon when Icon is Found in the EXE
       # icotool extracts all png files from ico files
       # Select and copy the best png image file by sorting using ls -S1.
       echo "${ICOTOOL_CMD} -x ${TEMP_DIR}/${EXE_LESS}.ico"
       ${ICOTOOL_CMD} -x "${TEMP_DIR}/${EXE_LESS}.ico" -o "${TEMP_DIR}" \
       2>/dev/null && \
       dbug "I: Script: ${FUNCNAME[0]}: Icotool: Extracting png files from" \
            "${TEMP_DIR}/${EXE_LESS}.ico" && \
       cp -f $(ls -S1 ${TEMP_DIR}/${EXE_LESS}*.png|head -n 1) \
                      "${ICONFILE}" && \
       dbug "I: Script: ${FUNCNAME[0]}: Copied successfully..." && WARN="false"

       # If icon could not be copied, warn the user
       if [ "${WARN}" != "false" ]; then
            dbug "I: Create Prefix: Icon could not be copied..." \
                 "use \"Change Icon...\" option"
            ${ZENITY_CMD} --error --no-wrap --title "Change Icon for ${EXE}" \
                 --text "Icon from ${GET_ICON} failed!"
       fi

       # Cleanup tempdir and clear variable
       unset WARN

       #remove tmp directory after copying icon png
       rm -rf "${TEMP_DIR}/*" && \
       dbug "I: Script: ${FUNCNAME[0]}: Cleanup ${TEMP_DIR}"
  elif [ "${GET_ICON_EXT}" = "ico" ]; then
         dbug "I: Script: ${FUNCNAME[0]}: .ico file selected to extract icon!"
         unset TEMP_DIR
         TEMP_DIR="${WINEZGUIDIR}/tmp"
         # Extract icon and convert it to several png files of diferent quality,
         # Create a temporary Directory to extract icon from the exe file
         dbug "I: Script: ${FUNCNAME[0]}: Extraction from ${GET_ICON}"
         mkdir -p ${TEMP_DIR} && \
         dbug "I: Script: ${FUNCNAME[0]}: Created directory ${TEMP_DIR}"

         ${ICOTOOL_CMD} -x "${GET_ICON}" -o "${TEMP_DIR}"  2>/dev/null && \
         dbug "I: Script: ${FUNCNAME[0]}: Icotool: Extracting png files from" \
              "${TEMP_DIR}/${EXE_LESS}.ico" && \
         cp -f $(ls -S1 ${TEMP_DIR}/*.png|head -n 1) "${ICONFILE}" && \
         dbug "I: Script: ${FUNCNAME[0]}: Copied successfully..." && WARN="false"

         # If icon could not be copied, warn the user
         if [ "${WARN}" != "false" ]; then
              dbug "I: Create Prefix: Icon could not be copied..." \
                   "use \"Change Icon...\" option"
              ${ZENITY_CMD} --error --no-wrap --title "Change Icon for ${EXE}" \
                   --text "Icon from ${GET_ICON} failed!"
         fi

         # Cleanup tempdir and clear variable
         unset WARN
  
         #remove tmp directory after copying icon png
         rm -rf "${TEMP_DIR}/*" && \
         dbug "I: Script: ${FUNCNAME[0]}: Cleanup ${TEMP_DIR}"

  else
       dbug "I: Script: ${FUNCNAME[0]}: ${GET_ICON} selected"
       cp -f "${GET_ICON}" "${ICONFILE}"
       export ICON="${ICONFILE}"
  fi

  export DESKTOP_FILE_EDIT="$(which desktop-file-edit)"

  # set icon to the user selected one
  ${DESKTOP_FILE_EDIT} --set-icon="${ICONFILE}" ${DESKTOPFILE} && \
  dbug "I: Script: ${FUNCNAME[0]}: Icon Changed Successfully!"
  # update icon in Info.yml
  if [ -w "${INFOFILE}" ]; then
       sed "s|Icon:.*|Icon:${ICONFILE}|g; t;" -i "${INFOFILE}" \
       && echo "Changed Icon file to ${ICONFILE}" \
       || echo "Cannot sed ${ICONFILE}"
  else 
       echo "E: Script: ${FUNCNAME[0]}: Cannot update ${INFOFILE}"
  fi

  # Clean up broken shortcuts and update shortcuts menu
  SOURCE "winezgui-remove-broken-links"
  winezgui-remove-broken-links

  #Set x permissions
  chmod +rx "${DESKTOPFILE}" "${SCRIPTFILE}" "${S_SCRIPTFILE}" "${S_DESKTOPFILE}"

  # Inform user
  #If script-change-icon_DO_NOT_PROMPT has no value then prompt
  #When we change exe, we do not want to see icon change prompt
  #The value will be set before calling this function by find-installed-exe
  if [ -z "${script-change-icon_DO_NOT_PROMPT}" ] ; then
       ${ZENITY_CMD} --info --no-wrap --title="${DESKTOPFILE}" --text="Icon Changed sucessfuly: ${GET_ICON}"
  fi
  # next time let it prompt
  unset script-change-icon_DO_NOT_PROMPT
  # Change Runtime Icon as soon as it is changed
  # Main Window is going to use ICON variable.
  export ICON="${ICONFILE}"

}
