#!/bin/bash

# track_sbo_tags.sh
#
# This is an example script to be run as a daemon.
# Every 30mins (as set by CHECK_INTERVAL) it will check
# whether SBo has a new tag and, if so, run update_repoData()
# which generates new repoData{pkl.stamp} and
# uploads to a public website.
#
# An update may be forced
# (bypassing daemon activity of checking SBo)
# by running this script with -f or --force-update argument
#
# Set SL_RELEASE in the environment to use a
# Slackware release other than the host system
#
# It is assumed a git clone of the SBo repository will be used
# which can be found by running `hoorex -c` (which implies
# that `hoorex -s ...` has been run sometime).
# Ensure git status of the repo is stable as this script
# will attempt to checkout the approriate branch -
# at the time of writing: master for 15.0, current for 15.0+
#
# Edit update_repoData() to reflect local locations/commands
# to upload to website.

# How often to interrogate SBo
CHECK_INTERVAL=1800 ;# 1800 = 30mins

# Slackware release
SL_RELEASE=${SL_RELEASE:-$(cut -d' ' -f 2 < /etc/slackware-version)}

# Working data location
SAVED_RELEASE_TITLE=$(mktemp -p /tmp SBoT-XXXXXXX)

set -e

# Run HooRex and update website with result
#
update_repoData() {
  # !!! Assume master and/or current branches are up to date !!!
  echo "Updating repoData"
  sbo_path=$(hoorex -c |grep sbo_path |cut -d' ' -f3)
  cd "$sbo_path"
    if [ "$SL_RELEASE" = "15.0" ]; then
      git checkout master
    elif [ "$SL_RELEASE" = "15.0+" ]; then
      git checkout current
    fi
  cd /storage/www.chriswilling.com/
    hoorex -f -p public_html/hoorex/"$SL_RELEASE"
    if [ -f public_html/hoorex/"$SL_RELEASE"/repoData.pkl ] && [ -f public_html/hoorex/"$SL_RELEASE"/repoData.stamp ]; then
      rsync -av public_html/ hostinger:domains/chriswilling.com/public_html/ || exit 4
    fi
}

if [ "$1" = "-f" ] || [ "$1" = "--force-update" ]; then
  update_repoData
  exit
fi

# First check
date
curl --silent https://github.com/SlackBuildsOrg/slackbuilds/tags.atom |grep ">$SL_RELEASE" | sort | tail -1 |sed -e 's/^[[:space:]]*<title>//' -e 's:</title>::' >"$SAVED_RELEASE_TITLE"
echo

until false ; do
    sleep $CHECK_INTERVAL

    date
    title_now="$(curl --silent https://github.com/SlackBuildsOrg/slackbuilds/tags.atom |grep ">$SL_RELEASE" | sort | tail -1 |sed -e 's/^[[:space:]]*<title>//' -e 's:</title>::')"
    echo "title_saved = $(cat "$SAVED_RELEASE_TITLE"), title_now = $title_now"
   	if [ "$(cat "$SAVED_RELEASE_TITLE")" != "$title_now" ]; then
        update_repoData
    	echo "$title_now" >"$SAVED_RELEASE_TITLE"
   	fi
    echo
done
