#!/bin/bash
###############################################################################
# Este script se dedica a descargarse los datos de EumetCast del FTP de
# blog.hochstaffl.eu que, generosamente, lo ofrece a otra gente.
#
# Este script está pensado para que lo ejecute el usuario sat.
#
# Marcos Molina Cano - 10/04/2017
###############################################################################

# Definción de fecha a usar.
unix_time=`date +%s`
resto=0
let resto=unix_time%900
let unix_time=unix_time-${resto}-900
YEAR=`date -u +%Y --date="@${unix_time}"`
MONTH=`date -u +%m --date="@${unix_time}"`
DAY=`date -u +%d --date="@${unix_time}"`
HOUR=`date -u +%H --date="@${unix_time}"`
MINUTES=`date -u +%M --date="@${unix_time}"`
fecha=`date -u +%Y%m%d%H%M --date="@${unix_time}"`

# Definición de fecha anterior para borrar directorios.
unix_time_old=0
let unix_time_old=unix_time-86400*2
YEAR_OLD=`date -u +%Y --date="@${unix_time_old}"`
MONTH_OLD=`date -u +%m --date="@${unix_time_old}"`
DAY_OLD=`date -u +%d --date="@${unix_time_old}"`
HOUR_OLD=`date -u +%H --date="@${unix_time_old}"`
MINUTES_OLD=`date -u +%M --date="@${unix_time_old}"`

#echo ${YEAR} ${MONTH} ${DAY} ${HOUR} ${MINUTES}
#echo ${YEAR_OLD} ${MONTH_OLD} ${DAY_OLD} ${HOUR_OLD} ${MINUTES_OLD}

#echo ${fecha}

# Lo primero, definimos el fichero de bloqueo y vemos si existe.
LOCK_FILE=/home/sat/hochstaffl_downloader_${fecha}.lock
if test -e ${LOCK_FILE} ; then
  echo "Archivo de bloqueo existente. Saliendo..."
  exit
else
  echo "Comienza el trabajo."
  touch ${LOCK_FILE}
fi

# Directorio donde se guardarán los datos que se van recibiendo.
WORK_DIR="/home/sat/from_msg/received"

# Datos del host, user y password.
HOST="eumetcast.hochstaffl.eu"
USER="MarcosMC"
PASS="marcosmc16"

# Definición de satélites, canales y segmentos por canal.
SAT=("MSG3________") # "GOES13" "GOES15")
CHAN_MSG3=("VIS006___" "VIS008___" "IR_016___" "IR_039___" "WV_062___" "WV_073___" \
           "IR_087___" "IR_097___" "IR_108___" "IR_120___" "IR_134___" "HRV______")
SEGM_MSG3=("8" "8" "8" "8" "8" "8" "8" "8" "8" "8" "8" "24")
#CHAN_GOES13=("00_7_075W" "03_9_75W" "06_6_075W" "10_7_075W")
#SEGM_GOES13=("7"         "7"        "7"         "7")
#CHAN_GOES15=(${CHAN_GOES13})
#SEGM_GOES15=(${SEGM_GOES13})

# Se comienza el trabajo en el directorio apropiado.
if test ! -d ${WORK_DIR}/${YEAR}${MONTH}${DAY}_${HOUR}${MINUTES} ; then
  mkdir -p ${WORK_DIR}/${YEAR}${MONTH}${DAY}_${HOUR}${MINUTES}
fi
cd ${WORK_DIR}/${YEAR}${MONTH}${DAY}_${HOUR}${MINUTES}

# Lo primero es comprobar que ya existe el fichero "prólogo" y, si existe,
# comprobamos que existe el fichero "epílogo". Si existen ambos entonces
# podemos proceder a descargar todos los datos.
PRO=H-000-MSG3__-MSG3________-_________-PRO______-${fecha}-__
EPI=H-000-MSG3__-MSG3________-_________-EPI______-${fecha}-__
if test -s ${PRO} ; then
  if test -s ${EPI} ; then
    echo "Todo existe en local. Pasemos a descargar datos."
  else
    touch ${EPI}.tmp \
    && wget -q ftp://${USER}:${PASS}@${HOST}/RawData/${YEAR}/${MONTH}/${DAY}/${EPI} \
    && rm ${EPI}.tmp
    if test -e ${EPI}.tmp ; then
      rm ${EPI}*
      echo "Problemas al descargar ${EPI}. Saliendo..."
      rm ${LOCK_FILE}
      exit
    fi
  fi
else
  touch ${PRO}.tmp \
  && wget -q ftp://${USER}:${PASS}@${HOST}/RawData/${YEAR}/${MONTH}/${DAY}/${PRO} \
  && rm ${PRO}.tmp
  if test -e ${PRO}.tmp ; then
    rm ${PRO}*
    echo "Problemas al descargar ${PRO}. Saliendo..."
    rm ${LOCK_FILE}
    exit
  fi
  touch ${EPI}.tmp \
  && wget -q ftp://${USER}:${PASS}@${HOST}/RawData/${YEAR}/${MONTH}/${DAY}/${EPI} \
  && rm ${EPI}.tmp
  if test -e ${EPI}.tmp ; then
    rm ${EPI}*
    echo "Problemas al descargar ${EPI}. Saliendo..."
    rm ${LOCK_FILE}
    exit
  fi
fi

aux_k=0
for ((i=0; i<${#SAT[@]}; i++)) ; do
  for ((j=0; j<${#CHAN_MSG3[@]}; j++)) ; do
    for ((k=0; k<${SEGM_MSG3[${j}]}; k++)) ; do
      let aux_k=${k}+1
      if test ${aux_k} -lt 10 ; then
        fichero="H-000-MSG3__-${SAT[${i}]}-${CHAN_MSG3[${j}]}-00000${aux_k}___-${fecha}-C_"
      else
        fichero="H-000-MSG3__-${SAT[${i}]}-${CHAN_MSG3[${j}]}-0000${aux_k}___-${fecha}-C_"
      fi
      if test -s ${fichero} ; then
        echo "${fichero} ya existe en local. Siguiente..."
        continue
      else
        wget -q ftp://${USER}:${PASS}@${HOST}/RawData/${YEAR}/${MONTH}/${DAY}/${fichero} -O ${fichero}.tmp \
        && mv ${fichero}.tmp ${fichero}
#        read -p "${fichero}"
        if test -e ${fichero}.tmp ; then
          rm ${fichero}*
          echo "Problemas al descargar ${fichero}. Siguiente..."
          continue
        fi
      fi
    done
  done
done

# Se ha acabado el trabajo. Limpiamos directorios que tengan más de dos días y
# borramos el fichero de bloqueo.
for n in `ls ${WORK_DIR}` ; do
  fecha_creacion=`stat -c %Y ${WORK_DIR}/${n}`
  fecha_tope=`date -u +%s --date="2 days ago"`
  if test ${fecha_creacion} -lt ${fecha_tope} ; then
    rm -r ${WORK_DIR}/${n}
  fi
done
rm ${LOCK_FILE}