#!/bin/bash

set -e 

FILE=$1
[ ! -w "$FILE" ] && echo first argument should be a writtable file && exit 1
jq -e . $FILE >/dev/null 2>&1 || (echo $FILE should be a json file && exit 1)
jq -e .version $FILE >/dev/null 2>&1 || (echo $FILE does not have a version field to increment && exit 1)

# looks for [string]-dev.[number]
# if not present returns [first].[second].[third+1]-dev.1
# else returns [string]-dev.[version+1]
inc_version() {
    jq '. + {"version": (if .version | contains("-dev") then [.version | match("^(.*)-dev.([0-9]*)$").captures[].string] | .[0] + "-dev." + (.[1]|tonumber|.+1|tostring) else [.version | match("^([0-9]*)\\.([0-9]*)\\.([0-9]*)$").captures[].string] | .[0] + "." + .[1] + "." + (.[2]|tonumber|.+1|tostring) + "-dev.1" end)}'
}

# read file
# replace version
# save to buffer
# write the same file
cat <<< $(cat $FILE | inc_version) > $FILE
