#!/usr/bin/env bash

# Requirements
# - Chef workstation
# - Access to chef server
# - Knife block plugin with configured sites
# - Berks plugin 
# - This script should be called from the base directory of the cookbook in question.

set -ex

COOKBOOK_NAME=$(basename $(pwd))
KNIFE_BINARY=$(/usr/bin/which knife)
BERKS_BINARY=$(/usr/bin/which berks)
KNIFE_BLOCK_VERSION=$(chef gem list --local | grep knife-block)

set +x

if [ -x ${KNIFE_BINARY} ] && [ -x ${BERKS_BINARY} ] && [[ ${KNIFE_BLOCK_VERSION} =~ "knife-block" ]]; then
  printf '%s\n' "Berks, Knife binaries and knife-block plugin found. Continuing..."
else
  printf '%s\n' "Berks, Knife binaries or knife-block plugin not found or executable." && exit 1
fi

for site in $(${KNIFE_BINARY} block list | grep '*' | awk '{print $2}'); do
  # Compare version on Chef server to local version.
  if [ -f 'metadata.rb' ]; then
    # Change to specific Chef server
    ${KNIFE_BINARY} block use "${site}"
    re='^[0-9]+$'
    # Check if cookbook exists. If so, check version. If not, upload.
    if [[ $(${KNIFE_BINARY} cookbook show ${COOKBOOK_NAME} 2>/dev/null | awk '{print $2}' | tr -d ".") =~ ${re} ]]; then
      old_version=$(${KNIFE_BINARY} cookbook show ${COOKBOOK_NAME} | awk '{print $2}' | tr -d ".")
      new_version=$(cat metadata.rb | grep -i version | awk '{print $2}' | tr -d "\'.")
      if [ "${new_version}" -gt "${old_version}" ]; then
        printf '%s\n' "Newer cookbook version detected. Continuing..." 
        ${BERKS_BINARY} install
        ${BERKS_BINARY} upload
      else
        printf '%s\n' "Newer cookbook version not found on ${site}!. Moving on to next site..."
      fi
    else
      printf '%s\n' "Cookbook not found on ${site}. Continuing with initial upload..."
      ${BERKS_BINARY} install
      ${BERKS_BINARY} upload
    fi
  else
    printf '%s\n' "metadata.rb not found!" && exit 1
  fi

done
