#!/bin/sh

#-----------------------------------------------------------------------
# VARIABLES
#-----------------------------------------------------------------------

# the warez dir
WAREZ="lib"
# remote
R_USER="warez"
R_HOST="ks3367494.wezee.eu"
R_PATH="/usr/local/warez"
# rsync
# bwlimit peutêtre défini à 2000 pour limiter la conso de bande passante
RSYNC_DAEMON="/usr/local/bin/rsync"
RSYNC_OPT="--quiet --recursive --update --compress --stats --human-readable --ipv4"
RSYNC_BWLIMIT="--bwlimit=6000"
# ssh
SSH_PORT="22420"
SSH_RSA="/home/lsm/.ssh/warez_id_rsa"
#local
L_USER="lsm"
L_GROUP="lsm"
L_PATH="/usr/local/download"

#-----------------------------------------------------------------------
# JOURNAL
#-----------------------------------------------------------------------

LOG_DIR="/var/log/warez"
if [ ! -d ${LOG_DIR} ]; then
  mkdir ${LOG_DIR}
fi
LOG="${LOG_DIR}/`date +%Y%m%d%H%M`.log"
touch ${LOG}

#-----------------------------------------------------------------------
# TESTS
#-----------------------------------------------------------------------

# le script est-il déjà en cours d'exécution ?
if [ -f "${LOCK}" ]; then
  printf "\n Warez job's is already in progress, we'll try again later...\n\n" >> ${LOG}
  exit 1
fi

# es-ce que $R_HOST est reachable ?
ping -c 3 ${R_HOST}
if [ "$?" -eq "0" ]; then
  printf "\n ${R_HOST} is reachable, let's go for the warez job's \n" >> ${LOG}
  else
  printf "\n HOUSTON we've lost ${R_HOST}, no warez job's for now :( \n" >> ${LOG}
  exit 1
fi

#
#-----------------------------------------------------------------------
# GRAB MOI TOUT CE VILAIN STUFF BRO'
#-----------------------------------------------------------------------
#

# we're starting bro'
LOCK="/tmp/frw.run"
touch ${LOCK}

# grab all of 'em
SSH="ssh -l ${R_USER} -i ${SSH_RSA} -p ${SSH_PORT}"
RSYNC="${RSYNC_DAEMON} ${RSYNC_OPT} ${RSYNC_BWLIMIT}"
${RSYNC} -e "${SSH}" ${R_USER}@${R_HOST}:${R_PATH}/${WAREZ} ${L_PATH}  >> ${LOG} 2>&1

# btw fix owner and permissions
chown -R ${L_USER}:${L_GROUP} ${L_PATH}/${WAREZ}  >> ${LOG} 2>&1
find ${L_PATH}/${WAREZ} -type d -exec chmod 755 {} \;  >> ${LOG} 2>&1
find ${L_PATH}/${WAREZ} -type f -exec chmod 644 {} \;  >> ${LOG} 2>&1

# we're done bro'
rm ${LOCK}
exit 0

#-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
#entrée dans le /etc/crontab
# 1st line is for normal days of the week
# 2nd line have to be commented if you're at home and need full Internet bandwidth!
# 3rd line is for week-end time
#23  1-10  * * mon,tue,wed,thu root  /bin/sh /root/fetch_remote_warez.sh
#32  11-17 * * mon,tue,wed,thu root  /bin/sh /root/fetch_remote_warez.sh
#23  5-10  * * fri,sat,sun     root  /bin/sh /root/fetch_remote_warez.sh

#mais je vais modifier ça, et faire tester au script la présence d'un fichier nowarez dans un rep accessible via samba, if true  = no warez job else