#!/bin/sh
. /etc/sorcery/local/config
. /etc/sorcery/roots
unset debug verbose paths

upstream_rel_get() {
  [ -z "$debug" ] || >&2 echo "D: Visiting $1"
  case "$HTTP_DL_HANDLER" in
    (curl) curl -s "$1" ;;
    (*) wget -q -O- "$1" ;;
  esac | gawk -vdebug="$debug" -vfname="$2" '
	{
		while (match(tolower($0), fname, V)) {
			if (debug) {
				printf "D: matched `%s`\n", \
					substr($0, RSTART, RLENGTH) \
					>"/dev/stderr"
			}
			print V[1 in V]
			$0 = substr($0, RSTART + RLENGTH)
		}
	}
  ' | sort -urV
}

# Process options
while
  case "$1" in
    (--test)
      shift
      upstream_rel_get "$@"
      exit
      ;;
    (--codex)
      CODEX_ROOT="$2"
      shift 2
      ;;
    (--debug)
      debug=1
      shift
      ;;
    (-v|--verbose)
      verbose=1
      shift
      ;;
    (-h|--help)
      cat <<"!"

sightsee [spell...]	Find upstream software releases. Takes paths or spell
			names.
!
      exit 0
      ;;
    (*) false ;;
  esac
do :
done

if [ $# = 0 ]; then
  paths="$CODEX_ROOT"
else
  for i in "$@"; do
    case "$i" in
      (*/*) ;;
      (*)
        if ! [ -d "$i" ]; then
          j=$(find "$CODEX_ROOT" -maxdepth 3 -name "$i" -type d -print -quit)
          [ -d "$j" ] && i="$j"
        fi
        ;;
    esac
    paths+=("$i")
  done
fi

find "${paths[@]}" -name DETAILS -exec awk -vdebug="$debug" '
	END { print_spell() }
	FNR==1 {
		if (spell != "") print_spell()
	}
	/^ *SPELL=/ {
		spell = $0
		sub(/^[^=]+=["'\'']?/, "", spell)
		sub(/["'\'']$/, "", spell)
		next
	}
	/^ *VERSION=/ {
		version = $0
		sub(/[\t ]*[;#].*/, "", version)
		sub(/.*=["'\'']?/, "", version)
		sub(/["'\'']$/, "", version)
		if (watch_url != "") nextfile
	}
	/^# *Watch:/ {
		sub(/^[^:]+: */, "")
		watch_url = $1
		sub(/^[^ ]+ */, "")
		watch_regex = $0
		if (version != "") nextfile
	}
	function print_spell() {
		if (watch_url == "") {
			printf "W: %s: %s\n", spell, \
				"Upstream releases page not specified" \
				>"/dev/stderr"
		} else {
			if (!watch_regex)
				watch_regex = spell \
					"[-_](R?[-_.+~0-9]+(([a-z]|rc|alpha|beta)[0-9]*)?)" \
					"([-.]src|[-.]source)?" \
					"[.](tar|zip|t[bgx]z|7z|sha?r|cpio|rpm|deb|[ot]tf)"
			if (debug)
				printf "D: regex `%s`\n", watch_regex >"/dev/stderr"
			print spell, version, watch_url, watch_regex
		}
		version = watch_url = spell = ""
	}
  ' {} + |
while read spell cur_rel url regex; do
  if [ -n "$debug" ]; then
    >&2 echo "D: current_release for $spell: $cur_rel"
  fi
  latest_rel=$(upstream_rel_get "$url" "$regex" | sed q) || continue
  if [ -z "$latest_rel" ]; then
    >&2 echo "W: $spell has no published releases, review the URL"
  elif [ "x$latest_rel" != "x$cur_rel" ]; then
    if [ -n "$debug" ]; then
      >&2 echo "D: latest release for $spell: $latest_rel"
    fi
    echo "$spell $latest_rel"
  elif [ -n "$verbose" ] || [ -n "$debug" ]; then
    >&2 echo "I: $spell is up to date"
  fi
done
