#!/bin/bash

OUTPUT_DIR=/mnt/dezign/work/

dz_notify() {
  mqueue_push -m /dzMsgIn -p "$1"
}

if [ "$#" -gt 0 ] ; then
  fullfime=$1
  TARGET_FILE=${OUTPUT_DIR}"${fullfime##*/}"
  out=$(wget -N -T 5 --no-check-certificate -nv -P ${OUTPUT_DIR} $1 2>&1)
  if [ ${#out} -gt 0 ] ; then
    if [[ $out == *"404: Not Found"* ]]; then
      echo "wget: file not present on remote side"
      exit 0
    elif [[ $out == *"-> \"${TARGET_FILE}\""* ]]; then
      echo "wget: file downloaded"
      exit 0
      sync
    elif [[ $out == *"hasn't got a known issuer"* ]]; then
      #do nothing
      :
    elif [[ $out == *"wurde von einem unbekannten Austeller herausgegeben"* ]]; then
      #do nothing
      :
    elif [[ $out == *"fehlgeschlagen: Verbindungsaufbau abgelehnt"* ]]; then
      echo "wget: server not running"
      exit 0
    elif [[ $out == *"Connection refused"* ]]; then
      echo "wget: server not running"
      exit 0
    else
      echo "wget: unhandled output present, continue parsing for file '$TARGET_FILE'"
      echo $out > ${OUTPUT_DIR}wget.log
    fi
  fi
  #output not exact enough
  out=$(wget -N -T 5 --no-check-certificate -P ${OUTPUT_DIR} $1 2>&1)
  if [ ${#out} -gt 0 ] ; then
    if [[ $out == *"Server file no newer than local file"* ]]; then
      echo "wget: allready present"
      exit 0
    elif [[ $out == *"Datei auf dem Server nicht neuer als die lokale Datei"* ]]; then
      echo "wget: allready present"
      exit 0
    elif [[ $out == *"Connection refused"* ]]; then
      echo "wget: server not running"
      exit 0
    elif [[ $out == *"fehlgeschlagen: Verbindungsaufbau abgelehnt"* ]]; then
      echo "wget: server not running"
      exit 0
    else
      echo "wget: verbose output present, continue parsing for file '$TARGET_FILE'"
      echo $out > ${OUTPUT_DIR}wget2.log
    fi
  else
    echo 'no verbose output present'
  fi
else
  dz_notify 'wrapWget: not enough parameter'
fi
