#!/bin/bash
# Rescapp Share Log run script
# Copyright (C) 2012,2013,2014,2015,2016,2017,2018,2019,2020 Adrian Gibanel Lopez
#
# Rescapp is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Rescapp is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Rescapp.  If not, see <http://www.gnu.org/licenses/>.
source ${RESCAPP_LIB_FILE}

SHARELOG_OK_STR="The log file was shared OK! :)"
SHARELOG_KO_STR="The log file sharing went wrong! :("
SHARELOG_FILES_NOT_FOUND="No logs to share were found or chosen."
SHARELOG_URL_NOT_FOUND="The log file could not be shared online."

# 1 parametre = Selected file
function rtux_share_log () {
local SELECTED_FILE="$1"

pastebinit -i "${RESCAPP_LOG_DIRECTORY}\
/${SELECTED_FILE}" -b ${RESCATUX_PASTEBIN_URL} \
-a resc_$$ -f bash

}

LOG_CHOOSE_STR="Please choose a log file"
LOG_STR="log"
PASTEBIN_HINT="Right-click and select copy. You will be able to paste it later in the chat option"
SHARE_LOG_RUNNING_STR="Sharing log."

m=1
for ffile in ${RESCAPP_LOG_DIRECTORY}/* ; do

  BFILE=$(basename $ffile)
  if [[ m -eq 1 ]] ; then
    LOG_LIST_VALUES="TRUE ${BFILE}"
  else
    LOG_LIST_VALUES="${LOG_LIST_VALUES} FALSE ${BFILE}"
  fi
  let m=m+1
done
# No need to check if there are no log files.
# selftest.log will always be there.


SELECTED_FILE=$(zenity ${ZENITY_COMMON_OPTIONS} \
	  --list  \
	  --text "${LOG_CHOOSE_STR}" \
	  --radiolist  \
	  --column "${SELECT_STR}" \
	  --column "${LOG_STR}" \
	  ${LOG_LIST_VALUES});

if [ "x${SELECTED_FILE}" != "x" ] ; then

  PASTEBIN_URL=$(rtux_Run_Show_Progress "${SHARE_LOG_RUNNING_STR}" rtux_share_log "${SELECTED_FILE}")
  if [ "x${PASTEBIN_URL}" != "x" ] ; then
    zenity ${ZENITY_COMMON_OPTIONS} \
      --entry \
      --text "${PASTEBIN_HINT}" \
      --entry-text="${PASTEBIN_URL}"

    rtux_Message_Success ${SHARELOG_OK_STR}
  else
    rtux_Message_Warning ${SHARELOG_URL_NOT_FOUND}
    rtux_Message_Failure ${SHARELOG_KO_STR}
  fi
else
  rtux_Message_Warning ${SHARELOG_FILES_NOT_FOUND}
  rtux_Message_Failure ${SHARELOG_KO_STR}
fi
