#!/bin/bash

# update latest available version in /var/run/.ncp-latest-version

TMPDIR="$( mktemp -d /tmp/ncp-check.XXXXXX || ( echo "Failed to create temp dir. Exiting" >&2; exit 1 ) )"
trap "rm -rf \"${TMPDIR}\"; exit 0" 0 1 2 3 15

git clone --depth 20 -q --bare https://github.com/nextcloud/nextcloudpi.git "$TMPDIR" || {
  echo "The git clone command failed: No connectivity to https://github.com ?" >&2
  exit 1
}

cd "$TMPDIR" || exit 1
VER=$( git describe --always --tags | grep -oP "v\d+\.\d+\.\d+" )
grep -qP "v\d+\.\d+\.\d+" <<< "$VER" && {       # check format
  echo "$VER" > /var/run/.ncp-latest-version

  # write changelog
  git log --graph --oneline --decorate \
    --pretty=format:"[%D] %s" --date=short | \
    grep 'tag: v' | \
    sed '/HEAD ->\|origin/s|\[.*\(tag: v[0-9]\+\.[0-9]\+\.[0-9]\+\).*\]|[\1]|' | \
    sed 's|* \[tag: |[|' > /usr/local/etc/ncp-changelog
}
cd / || exit 1
