bump_metadata_version () {
  if [ ! -f metadata.rb ]; then
    echo "Can't find metadata.rb in $(pwd)"
    return 1
  fi
  local OLD_VERSION=$(ruby -ane "print \$1 if /^version\s+'(.+)'/" metadata.rb)
  ruby -pe '$_.to_s.sub!(/^(version.+)(\d+)/) { "#{$1}#{$2.to_i + 1}" }' -i metadata.rb
  local NEW_VERSION=$(ruby -ane "print \$1 if /^version\s+'(.+)'/" metadata.rb)
  APPNAME=$(basename $(pwd))
  if [[ $APPNAME == app_* ]]; then
    berks update $APPNAME > /dev/null
  fi
  echo "Updated $OLD_VERSION to $NEW_VERSION"
}

push_metadata_version () {
  APPNAME=$(basename $(pwd))
  if [ ! -f metadata.rb ]; then
    echo "Can't find metadata.rb in $(pwd)"
    return 1
  fi
  local VERSION=$(ruby -ane "print \$1 if /^version\s+'(.+)'/" metadata.rb)
  if [[ $APPNAME == app_* ]]; then
		git commit -m "bump version to $VERSION" metadata.rb Berksfile.lock && git push && git tag $VERSION && git push --tags
  else
		git commit -m "bump version to $VERSION" metadata.rb && git push && git tag $VERSION && git push --tags
  fi
}

upload_and_apply () {
  APPNAME=$(basename $(pwd))
  PARENT=$(basename $(dirname $(pwd)))

  if [ "$1" = "--force-yes" ]; then
    FORCEYES=true
  fi

  if [[ $APPNAME != app_* ]] || [ $PARENT != cookbooks  ]; then
    echo "It doesn't look like $(pwd) is an app cookbook"
    return 1
  fi

  if [ ! -f environments.txt ]; then
    echo "Can't find environments.txt in $(pwd)"
    return 1
  fi

  berks upload

  for env in $(cat environments.txt); do
    if [ "$FORCEYES" = true ]; then
      echo $env
      berks apply $env
      echo
    else
      while true; do
				printf "Do you wish to apply $APPNAME to $env? (y/n): "
  			read ync
  			case $ync in
          [Yy]* ) berks apply $env; break;;
          [Nn]* ) break;;
	  			* ) break;;
	  		esac
	  	done
    fi
  done
}

create_environments () {
	APPNAME=$(basename $(pwd))
  PARENT=$(basename $(dirname $(pwd)))
  if [[ $APPNAME != app_* ]] || [ $PARENT != cookbooks  ]; then
    echo "It doesn't look like $(pwd) is an app cookbook"
    return 1
  fi

	if [ ! -f environments.txt ]; then
    echo "Can't find environments.txt in $(pwd)"
    return 1
  fi

  for env in $(cat environments.txt); do
    knife environment show $env > /dev/null 2>&1
    if [ $? -eq 100 ]; then
      knife environment create $env -d "Generated by cpe-core"
    fi
  done

}
