function get_arg {
  local value=${1}
  local default=${2}

  if [ ${value} ]; then
    echo ${value}
  else
    echo ${default}
  fi
}

function download_source {
  local url=${1}
  local branch=${2}
  local dir=${3}
  local path=${4}

  if [ -d ${dir} ]; then
    rm -Rf ${dir};
  fi
  git -c core.sshCommand="ssh -o StrictHostKeyChecking=no" clone --quiet -b ${branch} --depth=1 ${url} ${dir}${path}
}

function pack_source {
  local filename=${1}
  local src_path=${2}

  zip ${filename} -r ${src_path} -x \*.git\* -9 -q
}

function write_version {
  local npm_file=${1}
  local version=${2}

  sedi 's|"version": "[0-9][0-9a-zA-Z._-]*"|"version": "'"${version}"'"|' ${npm_file}
}

function write_docker_image_version {
  local docker_composer_file=${1}
  local docker_image=${2}
  local version=${3}

  sedi 's|'"${docker_image}"':[0-9a-zA-Z -_]*|'"${docker_image}"':'"${version}"'|' ${docker_composer_file}
}

function sedi {
  if [ "$(uname)" == "Linux" ] || [[ "$(uname)" == MINGW* ]] || [[ "$(uname)" == MSYS* ]]; then
    sed -i "$@"
  else
    sed -i "" "$@"
  fi
}

function notifyToSlack() {
  local webhookUrl=${1}
  local message=${2}

  curl --silent --output /dev/null --data-urlencode \
    "$(printf 'payload={\"text\": \"%s\"}' \
      "${message}" \
    )" \
    ${webhookUrl}
}

function get_version {
  local package_file=${1:-"package.json"}
  if [ ! -f "${package_file}" ]; then
    echo ""
    return 1
  fi

  local version=$(grep -o '"version"[ ]*:[ ]*"[^"]*"' "${package_file}" | head -1 | sed 's/.*: *"\([^"]*\)".*/\1/')
  if [ -z "$version" ]; then
    echo ""
    return 1
  fi

  echo ${version}
}
