#!/bin/sh
set -eu

echo "[build pipeline] rewriting .env.version" >&2

if [ -f ./.env.version ]; then
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      ''|\#*) continue ;;
    esac
    if printf '%s' "$line" | grep -Eq '^[[:alpha:]_][[:alnum:]_]*='; then
      key="${line%%=*}"
      value="${line#*=}"
      export "$key=$value"
    fi
  done < ./.env.version
fi

if [ -n "${WOODPECKER_COMMIT:-}" ]; then
  GIT_REV="$(printf '%s' "${WOODPECKER_COMMIT}" | cut -c1-7)"
elif command -v git >/dev/null 2>&1; then
  GIT_REV="$(git rev-parse --short HEAD 2>/dev/null || true)"
fi
: "${GIT_REV:=dev}"

if [ -n "${WOODPECKER_BRANCH:-}" ]; then
  BUILD_BRANCH="${WOODPECKER_BRANCH}"
elif command -v git >/dev/null 2>&1; then
  BUILD_BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
fi
: "${BUILD_BRANCH:=local}"

if [ -f version ]; then
  APP_V="$(cat version 2>/dev/null || true)"
fi
: "${APP_V:=dev}"

if [ -z "${BUILD_DATE:-}" ]; then
  BUILD_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo unknown)"
fi

: "${WOODPECKER_MACHINE:=woodpecker}"
if [ -z "${BUILD_USER:-}" ]; then
  BUILD_USER="${WOODPECKER_MACHINE}"
fi

cat > .env.version <<EOF
GIT_REV=${GIT_REV}
BUILD_BRANCH=${BUILD_BRANCH}
APP_V=${APP_V}
BUILD_DATE=${BUILD_DATE}
BUILD_USER=${BUILD_USER}
EOF
