#!/usr/bin/env bash
# Copyright Ken Fallon - Released into the public domain. http://creativecommons.org/publicdomain/ 
#============================================================

upload_dir="/home/hpr/upload"
reserve_dir="/home/hpr/reserve"
hub_dir="/home/hpr/hub"
reserve_file="${hub_dir}/reserve.txt"

while read reserve_show_dir
do
  echo "Processing \"${reserve_show_dir}\""
  shownotes="${reserve_show_dir}/shownotes.json"
  if [ ! -s "${shownotes}" ]
  then
    echo "ERROR: \"${shownotes}\" not found"
    exit 1
  fi
  host_id="$( jq --raw-output '.host.Host_ID' "${shownotes}" )"
  if [ "${host_id}" -eq "0" ]
  then
    echo "ERROR: New host detected \"${host_id}\" post the first show to the regular queue."
    exit 1
  fi
  
  metadata_url="$( jq --raw-output '.metadata.url' "${shownotes}" )"
  if [ -n "${metadata_url}" ]
  then
    save_name=$( basename "${metadata_url}" | sed -e 's/[^A-Za-z0-9.]/_/g' -e 's/__/_/g' )
    wget "${metadata_url}" -O "${reserve_show_dir}/${save_name}"
    if [ ! -s "${reserve_show_dir}/${save_name}" ]
    then
      echo "ERROR: \"${metadata_url}\" needs to be downloaded as \"${reserve_show_dir}/${save_name}\""
      exit 1
    fi    
  fi
  Host_ID="$( jq --raw-output '.host.Host_ID' "${shownotes}" )"
  Host_Name="$( jq --raw-output '.host.Host_Name' "${shownotes}" | sed -e 's/[^A-Za-z0-9]/_/g' -e 's/__/_/g' )"
  Key="$( jq --raw-output '.metadata.Key' "${shownotes}" )"
  Timestamp="$( jq --raw-output '.metadata.Timestamp' "${shownotes}" )"
  Title="$( jq --raw-output '.episode.Title' "${shownotes}" | sed -e 's/[^A-Za-z0-9]/_/g' -e 's/__/_/g')"
  Timestamp_Epoch="$( \date -u +%s -d "${Timestamp}" )"
  mv -v "${reserve_show_dir}" "${reserve_dir}/${Timestamp_Epoch}_${Host_ID}_${Key}_${Host_Name}_${Title}"
done  < <( find "${upload_dir}" -type d -iname "*_9999_*" )

detox -r -v "${reserve_dir}"

ls -1 "${reserve_dir}" | awk -F '_' '{ $2=""; $3=""; print}' | while read line
do
  upload_epoch="$( echo "${line}" | awk '{print $1}' )"
  upload_iso8601="$( \date -d "@${upload_epoch}" +%Y-%m-%d )"
  echo "${upload_iso8601} $( echo ${line} | awk '{ $1=""; print}' )"
done > "${reserve_file}"
nl "${reserve_file}"
