#!/bin/sh

#
# Copyright:: Copyright (c) 2020 Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# Perform necessary setup steps
# after package is installed.
#

PROGNAME=`basename $0`
INSTALLER_DIR=/opt/cinc-workstation

error_exit()
{
  echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
  exit 1
}

is_darwin()
{
  uname -a | grep "^Darwin" 2>&1 >/dev/null
}

if is_darwin; then
    PREFIX="/usr/local"
    mkdir -p "$PREFIX/bin"
else
    PREFIX="/usr"
fi

hab_target_path="$PREFIX/bin/hab"
if [ -L "$hab_target_path" ]; then
  # If the link exists, always remove it because we replace it later in script anyway.
  loc=$(readlink "$hab_target_path")
  case $loc in
    *chef-workstation*)
      # We own this path, so we're not taking it over from another install.
      ;;
    *)
      takeover="1"
  esac
elif [ -f "$hab_target_path" ]; then
  # Preserve the original target path
  mv "$hab_target_path" "$hab_target_path.orig"
  takeover="1"
  moved="1"
fi

if [ "$takeover" = "1" ]; then
  echo ""
  echo "NOTE: Chef Habitat on this node is now managed by Chef Workstation."
  echo "      Future Workstation updates will always include the latest stable"
  echo "      Habitat release."
  echo ""
fi

if [ "$moved" = "1" ]; then
  echo "      Original habitat binary has been moved to '$hab_target_path.orig'"
  echo ""
fi

binaries="cinc-run berks cinc cinc-cli cinc-analyze cinc-apply cinc-shell cinc-solo chef-vault cookstyle delivery foodcritic cinc-auditor kitchen knife ohai cinc-client hab chef-apply chef-client chef-shell chef-solo inspec cinc-zero mixlib-install fauxhai"
for binary in $binaries; do
  ln -sf "$INSTALLER_DIR/bin/$binary" $PREFIX/bin || error_exit "Cannot link $binary to $PREFIX/bin"
done

wrapper_links="chef chef-cli chef-analyze chef-run"
link_target="cinc-wrapper"
for link in $wrapper_links; do
  if [ ! -e $PREFIX/bin/$link ]; then
    echo "Symlinking $link command to cinc-wrapper for compatibility..."
    ln -sf $INSTALLER_DIR/bin/$link_target $PREFIX/bin/$link || error_exit "Cannot link $link_target to $PREFIX/bin/$link"
  fi
done

if is_darwin; then
  ln -sf $INSTALLER_DIR/bin/uninstall_chef_workstation $PREFIX/bin || error_exit "Cannot link uninstall_chef_workstation to $PREFIX/bin"
fi

echo ""
echo "Thank you for installing Cinc Workstation!"
echo "You can find some tips on getting started at https://cinc.sh/"
echo ""
exit 0
