#!/bin/sh

_old_pwd=$(pwd)
_tmpdir="/tmp/fetch_subrepo_$$"

die () {
  echo $1; exit 1
}
version_greater_equal() {
  printf '%s\n%s\n' "$2" "$1" | sort -V -C
}
command -v yq 2>&1 >/dev/null || die ">> missing yq"
#version_greater_equal "$( git --version | awk '{print $3}')" 2.25 || die ">> require git version 2.25 or above"


version=$(curl https://raw.githubusercontent.com/snowdrop/godaddy-webhook/master/deploy/godaddy-webhook/Chart.yaml 2>/dev/null| yq e '.version' - )
base_repo=https://github.com/snowdrop/godaddy-webhook
sub_dir=deploy/godaddy-webhook
branch=master

test -d $version && die "version $version exist.."
test ! -d $version \
  && mkdir $_tmpdir \
  && cd $_tmpdir \
  && git init \
  && git config core.sparseCheckout true \
  && git remote add origin $base_repo \
  && echo "$sub_dir" > .git/info/sparse-checkout \
  && git pull --depth=1 origin $branch \
  && mv -v "${_tmpdir}/${sub_dir}" "$_old_pwd/$version" \
  && rm -rf ${_tmpdir} \
  && cd $_old_pwd

