#!/bin/bash

# given in disk version information, return 0 if an update is available

NEED_UPDATE=false
VERFILE=/var/run/.ncp-latest-version

[[ $( cat $VERFILE 2>/dev/null | wc -c ) -eq 0 ]] && ncp-check-version

if grep -qP "v\d+\.\d+\.\d+" $VERFILE; then

  MAJOR=$( grep -oP "\d+\.\d+\.\d+" $VERFILE | cut -d. -f1 )
  MINOR=$( grep -oP "\d+\.\d+\.\d+" $VERFILE | cut -d. -f2 )
  PATCH=$( grep -oP "\d+\.\d+\.\d+" $VERFILE | cut -d. -f3 )

  MAJ=$( grep -oP "\d+\.\d+\.\d+" /usr/local/etc/ncp-version | cut -d. -f1 )
  MIN=$( grep -oP "\d+\.\d+\.\d+" /usr/local/etc/ncp-version | cut -d. -f2 )
  PAT=$( grep -oP "\d+\.\d+\.\d+" /usr/local/etc/ncp-version | cut -d. -f3 )

  if [ "$MAJOR" -gt "$MAJ" ]; then
    NEED_UPDATE=true
  elif [ "$MAJOR" -eq "$MAJ" ] && [ "$MINOR" -gt "$MIN" ]; then
    NEED_UPDATE=true
  elif [ "$MAJOR" -eq "$MAJ" ] && [ "$MINOR" -eq "$MIN" ] && [ "$PATCH" -gt "$PAT" ]; then
    NEED_UPDATE=true
  fi
fi
[[ "$NEED_UPDATE" == "true" ]] && exit 0
