#!/bin/bash

# update latest NextCloudPi code from github

[[ -z "$DBG" ]] || set -$DBG

if [[ -f /.dockerenv ]] || [[ -f /.docker-image ]] || [[ "$DOCKERBUILD" == 1 ]]
then
  echo "WARNING: Docker images should be updated by replacing the container from the latest docker image" \
    "(refer to the documentation for instructions: https://docs.nextcloudpi.com)." \
    "If you are sure that you know what you are doing, you can still execute the update script by running it like this:"
  echo "> ALLOW_UPDATE_SCRIPT=1 ncp-update"
  [[ "$ALLOW_UPDATE_SCRIPT" == "1" ]] || exit 1
fi

{
  [ "$(id -u)" -ne 0 ] && { printf "Must be run as root. Try 'sudo $0'\n"; exit 1; }

  BRANCH="${1:-master}"
  [[ "$BRANCH" != "master" ]] && echo "INFO: updating to development branch '$BRANCH'"

  TEMPDIR="$( mktemp -d /tmp/ncp-update.XXXXXX || ( echo "Failed to create temp dir. Exiting" >&2; exit 1 ) )"
  trap 'cd /; rm -rf "${TEMPDIR}"' EXIT

  echo -e "Downloading updates"
  git clone --depth 20 -b "$BRANCH" -q https://github.com/nextcloud/nextcloudpi.git "$TEMPDIR" || {
    echo "No internet connectivity"
    exit 1
  }

  # shellcheck disable=SC2164
  [[ -f /.ncp-image ]] || {
    cd "$TEMPDIR"         # update locally during build

    [[ -z "$2" ]] || {
      git fetch origin "$2" || {
        echo "Error: Could not fetch $2"
        exit 1
      }
      git checkout FETCH_HEAD
    }
  }

  echo -e "Performing updates"
  ./update.sh || exit $?

  cd "$TEMPDIR" || exit 1
  git describe --always --tags --abbrev=0 2>/dev/null | grep -qoP "v\d+\.\d+\.\d+" || git fetch --unshallow --tags -q
  VER=$( git describe --always --tags --abbrev=0 | grep -oP "v\d+\.\d+\.\d+" )

  # check format
  grep -qP "v\d+\.\d+\.\d+" <<< "$VER" || { echo "Error: missing version"; exit 1; }

  echo "$VER" > /usr/local/etc/ncp-version
  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

  echo -e "NextCloudPi updated to version $VER"
  exit 0

} # force to read the whole thing into memory, as its contents might change in update.sh
