#!/bin/sh
echo $0

if [ ! -d /zTools/zPrivateConfig ] && [ -d /static ]
then
	BASE=/static
fi

if [ -d /zTools/zPrivateConfig ] && [ ! -d /static ] 
then
	BASE=/zTools/zPrivateConfig
fi

if [ -d /zTools/zShared ]
then
	BASE=/zTools/zShared
fi

if [  -d /static ] && [ ! -d /zTools/zShared ] && [ ! -d /zTools/zPrivateConfig ]
then
	BASE=/static
fi

if [ ! -d /static ] && [ -d /zTools/zShared ] && [ ! -d /zTools/zPrivateConfig ]
then
	BASE=/zTools/zShared
fi

if [ ! -d /static ] && [ ! -d /zTools/zShared ] && [ -d /zTools/zPrivateConfig ]
then
	BASE=/zTools/zPrivateConfig
fi

MYNAME=$(uname -n)
if [ -d /volume12/zTools/Sync${MYNAME}/zTools/zSyno ]
then
	BASE=/volume12/zTools/Sync${MYNAME}/zTools/zSyno
fi

if [ -f ${BASE}/secrets/.telegramenv ]
then
  . ${BASE}/secrets/.telegramenv
else
  if [ -z ${DUFUS+x} ]
  then
    mkdir -p /static/secrets
    echo "Created ${BASE}/secrets/.telegramenv"
    echo "Please update contents and rerun"
    echo "DUFUS="" " > ${BASE}/secrets/.telegramenv
    echo "TCHATID="" " >> ${BASE}/secrets/.telegramenv
    exit 1
  else
    mkdir -p /static/secrets
    echo "DUFUS=${DUFUS}" > ${BASE}/secrets/.telegramenv
    echo "TCHATID=${TCHATID}" > ${BASE}/secrets/.telegramenv
  fi
fi

SCRIPT=$1
MSG=$2
FILETOSEND=$3
MYNAME=`uname -n`

MSG=/var/tmp/${THIS_SCRIPT}.msg.$$
#if [ -e ${ERROR} ]
# then
#  echo "---error_log_start"       >> ${MSG}
#  cat ${ERROR}                    >> ${MSG}
#  echo "---error_log_finish"      >> ${MSG}

SUBJECT=" ${MYNAME} - ${SCRIPT}: "

cat ${FILETOSEND} > ${MSG}.txt
FILE='document=@'"${MSG}.txt"

curl -X POST \
     -F ${FILE} \
     -F "chat_id=${TCHATID}" \
     -F "caption=${SUBJECT} ${MSG}" \
     https://api.telegram.org/bot${DUFUS}/sendDocument

rm -f ${MSG}
