#!/bin/bash

OUTPUT_DIR=/mnt/dezign/work/

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


check_file() {
  URL=$1
  local_file=$2
  # current output format: 16 Apr 2020 08:14:26
  #remote_last_modified_date="$(curl --insecure -sI $1 | grep -E 'Last-Modified:' | awk '{print $3,$4,$5,$6}' )"
  
  parsed_remote_last_modified_date="$(date +%s -d "$(curl --insecure -sI ${URL} | grep -E 'Last-Modified:' | awk '{print $3,$4,$5,$6}' )")"
  echo "remote: $parsed_remote_last_modified_date"
  
  parsed_local_last_modified_date="$(date +'%s' -r "$local_file")"
  echo "local:  $parsed_local_last_modified_date"
  
  if [ $parsed_remote_last_modified_date -gt $parsed_local_last_modified_date ] ; then
    echo "remote file is newer"
  fi
}

if [ "$#" -gt 1 ] ; then
  LOCALFILE=$2
  LOCALFILE_TMP=${LOCALFILE}~
  REMOTEFILE=$1
  CURL_COMMAND=""
  if [ -f "${LOCALFILE}" ]; then
    CURL_COMMAND="-z ${LOCALFILE}"
  fi
  out=$(curl -w '%{http_code}\n' --insecure -sS ${CURL_COMMAND} -o ${LOCALFILE_TMP} --remote-time ${REMOTEFILE} 2>&1)
  status=$?

  if [ "$status" -eq 0 ]; then
    if [ "$out" -eq 200 ]; then
      #download again
      out=$(curl -w '%{http_code}\n' --insecure -sS ${CURL_COMMAND} -o ${LOCALFILE_TMP} --remote-time ${REMOTEFILE} 2>&1)
      if [ "$out" -eq 200 ]; then
        if [ -f "${LOCALFILE_TMP}" ]; then
          #move to final destination
          mv -f ${LOCALFILE_TMP} ${LOCALFILE}
        fi
      fi
    fi
    echo "curl http: ${out}"
  else
    rm -f ${LOCALFILE_TMP}
    echo "curl error: ${status}"
  fi
fi