#!/usr/bin/env bash
# Launch the Script file
#
# 1. Test if the given exe exists (if not found ask user to locate it)
# 2. Goto Game Directory
# 3. Launch The EXE file
# 4. After the Launch if lnk and .desktop files are found inside wine prefix
script-launch()
{
  dbug "I: Script: Launched ${FUNCNAME[0]}"
  
  SOURCE "script-check-variables-loaded-or-not"
  script-check-variables-loaded-or-not
  FOUND_EXE_FILES="${PREFIXDIR}/found-exe-files.yml"
  if [ -z "${1}" ]; then
       # 1. Test if the given exe exists (if not found ask user to locate it)
       SOURCE "script-locate-exe-function"
       script-locate-exe-function
       exe_name=$(basename "${EXE_FILE}")
       exe_path=$(dirname  "${EXE_FILE}")
  else # Use passed argument as exe file
       exe_name=$(basename "${1}")
       exe_path=$(dirname  "${1}")
  fi
  # 2. Goto Game Directory
  cd "${exe_path}"
  dbug "I: Script: Launching ${exe_name}"

  # Environment Variable to be set before launching wine + exe
  if [ -f "${PREFIXDIR}/environment-variable.yml" ]; then
       dbug "I: Script: found CMDLINE arguments"
       ENVIRONMENT_VARIABLE=$(grep args "${PREFIXDIR}/environment-variable.yml"|cut -f2 -d ":")
       dbug "I: Script: environment-variable=${ENVIRONMENT_VARIABLE}"
       dbug "------------------------------------------------"
       # export only when found in environment-variable.yml and not it is not empty
       if ! [ -z "${ENVIRONMENT_VARIABLE}" ]; then
          export "${ENVIRONMENT_VARIABLE}"
       fi
  fi

  # CMDLINE exe argument 
  if [ -f "${PREFIXDIR}/cmdline.yml" ]; then
       dbug "I: Script: found CMDLINE arguments"
       EXE_ARGUMENTS=$(grep args "${PREFIXDIR}/cmdline.yml"|cut -f2 -d ":")
       dbug "I: Script: args=${EXE_ARGUMENTS}"
  fi

  # Check runner whether it is present and working

  # /app/bin/wine will always be not found by script
  # manually test it with flatpak command
  # If ${FLATPAK_NAME} is installed, and script created using flatpak
 if  [ ${INSTALL_TYPE} = "flatpak" ] && \
     [ $(flatpak --command=echo run ${FLATPAK_NAME} 0 2>/dev/null) ]; then
       WINEVER_TEST="$(flatpak run --command=${RUNNER} ${FLATPAK_NAME} --version)"
 else
     # flatpak install and running from shell inside flatpak winezgui
      if [ "${INSTALL_TYPE}" = "flatpak" ]; then
           dbug "I: Script: Install type: Flatpak, Running from flatpak!"
           WINEVER_TEST="$(${RUNNER} --version)"
      else
           # We are using non flatpak install
           dbug "I: Script: Install type: System, Running from host!"
           WINEVER_TEST="$(${RUNNER} --version)"
      fi
fi

# If runner fails to run then, it is absent, let's inform the user
if [ -z "${WINEVER_TEST}" ]; then

     # based on runner file, set runner name for the missing runner
     if   [ "${RUNNER}" = "${SYSTEM_WINE}" ]; then
            export RUNNER_NAME="System Default"
     elif [[ "$RUNNER" == *"files/bin/wine" ]]; then
            export RUNNER_NAME=$(basename $(echo ${RUNNER}|sed "s|/files/bin/wine||g"))
     elif [[ "$RUNNER" == *"/bin/wine" ]]; then
            export RUNNER_NAME=$(basename $(echo ${RUNNER}|sed "s|/bin/wine||g"))
     fi
     
     unset TEXTMSG
     TEXTMSG+="Runner: <b>${RUNNER_NAME}</b> is missing\n"
     TEXTMSG+="<b>${RUNNER}</b>\n"
     TEXTMSG+="Would you like to see <b>Runner Options</b>\?"
     unset TITLEMSG
     TITLEMSG+="<b>${APP_WITH_VER}: ${RUNNER_NAME} Not Found</b>"
     # Inform and let user choose Runner options
     ${ZENITY_CMD} --question --width 400 --title "${TITLEMSG}" --text "${TEXTMSG}"
     ANSWER=$?
     if [ ${ANSWER} -eq 0 ]; then
          SOURCE "script-runner-not-found-options"
          script-runner-not-found-options
     fi 
fi
  # WINE_CMD will be updated by SCRIPTFILE which is calling this function
  # Check for Wine version change
  
  CURRENT_WINE_VERSION="$(${WINE_CMD} --version)"
  CREATED_WINE_VERSION=$(grep -i "Wine:" ${INFOFILE}|cut -f2 -d ":")
  dbug "I: Script: Created using Wine Version:${CREATED_WINE_VERSION}"
  dbug "I: Script: Current Wine Version is   :${CURRENT_WINE_VERSION}"

  echo '--------------------------------- Wine CMD --------------------'
  echo "WINE_CMD = $WINE_CMD"
  echo "CURRENT_WINE_VERSION = $CURRENT_WINE_VERSION"
  echo "CREATED_WINE_VERSION = $CREATED_WINE_VERSION"
  

  if [ "${CURRENT_WINE_VERSION}" != "${CREATED_WINE_VERSION}" ]; then
       dbug "I: Script: Wine Version is different!"
       unset TEXTMSG
       TEXTMSG+="Created using Wine Version:${CREATED_WINE_VERSION}\n"
       TEXTMSG+="Current Wine Version is   :${CURRENT_WINE_VERSION}\n"
       TEXTMSG+="Update version Info?"
       unset TITLEMSG
       TITLEMSG+="Wine version mismatch!"

       ${ZENITY_CMD} --question --width 400 --title "${TITLEMSG}" --text "${TEXTMSG}"
       ANSWER=$?
       if [ ${ANSWER} -eq 0 ] && [ -w "${INFOFILE}" ]; then
            sed "s|Wine:.*|Wine:${CURRENT_WINE_VERSION}|g; t;" -i "${INFOFILE}" \
            || echo "Failed Updating: Info.yml:Wine:${CURRENT_WINE_VERSION}"
            dbug "I: Script: Updated wine version to ${CURRENT_WINE_VERSION}"
       fi
  fi
  


  # 3. Launch The EXE file
     echo "7. --------------------------------------- RUNNER = $RUNNER"
     echo "7. --------------------------------------- WINE_CMD = $WINE_CMD"

  echo "${WINE_CMD} ${exe_name} ${EXE_ARGUMENTS}"

  ${WINE_CMD} "${exe_name}" ${EXE_ARGUMENTS}

  # 4. Remove wine installed shortcuts, unclutters menu
  SOURCE "winezgui-remove-wine-created-shortcuts"
  winezgui-remove-wine-created-shortcuts

  # Detect Setup or Direct Play exe
#   TEST_NAME=$(echo "${exe_name}"| tr [A-Z] [a-z]) # Change case to test
#   if [[ "${TEST_NAME}" == *"setup"* ]]   2>/dev/null || \
#      [[ "${TEST_NAME}" == *"install"* ]] ; then
#        dbug "I: Script: Launching =-= SETUP INSTALLER =-="
#      #   SOURCE "script-change-exe-and-prefix"
#      #   script-change-exe-and-prefix
#        SOURCE "script-create-shortcuts-for-found-exes"
#        script-create-shortcuts-for-found-exes
#   else
#        dbug "I: Script: Launching script find exe"
#        SOURCE "script-find-installed-exe"
#        script-find-installed-exe
#   fi
  # On 1st run create shortcuts for all found exe
  if [ -f "${FOUND_EXE_FILES}" ]; then
       dbug "script-launch: FOUND_EXE_FILES..."
       SOURCE "script-find-installed-exe"
       script-find-installed-exe

       
  else # from 2nd run onwards, detect new exe files.
       dbug "I: script-launch: 1st launch detected........................"
       SOURCE "script-create-shortcuts-for-found-exes"
       script-create-shortcuts-for-found-exes 
  fi
}
