#!/bin/bash
#
# Update Tvheadend version file (if required)
#

# Path to version file
FILE=$1

# Calculate version
if [ -d ".git" ]; then
  VER=$(cd "$(dirname "$0")"/..; git describe --dirty --match "v*" 2> /dev/null)
  if [ $? -ne 0 ]; then
    # Git describe failed, maybe "--dirty" option is not available
    # Adding "-unknown" postfix to mark this situation
    VER=$(cd "$(dirname "$0")/.."; git describe --match "v*" 2> /dev/null)-unknown
  fi
  VER=$(echo $VER | sed "s/^v//" | sed "s/-\([0-9]*\)-\(g[0-9a-f]*\)/.\1~\2/")
elif [ -f "$(dirname "$0")/../debian/changelog" ]; then
  VER=$(head -1 "$(dirname "$0")/../debian/changelog" | awk '{ print $2 }' | tr -d '()' | cut -d '-' -f 1)
else
  VER="0.0.0~unknown"
fi

# Output
if [ -z "$FILE" ]; then
  echo $VER
  exit
fi

# Leave (probably ppa build)
if [ -z "$VER" -a -s "$FILE" ]; then
  cat "$FILE"
  exit
fi

# Update?
NEW_VER="const char *tvheadend_version = \"$VER\";"
OLD_VER=$(cat "$FILE" 2> /dev/null)
if [ "$NEW_VER" != "$OLD_VER" ]; then
  echo $NEW_VER > "$FILE"
fi
echo $VER