#!/bin/sh -e
#
# INTEL CONFIDENTIAL
#
# Copyright (c) 2022 Intel Corporation
# All Rights Reserved.
#
# This software and the related documents are Intel copyrighted materials,
# and your use of them is governed by the express license under which they
# were provided to you ("License"). Unless the License provides otherwise,
# you may not use, modify, copy, publish, distribute, disclose or transmit this
# software or the related documents without Intel's prior written permission.
#
# This software and the related documents are provided as is, with no express or
# implied warranties, other than those that are expressly stated in the License.
#

readonly MY_PATH=$(realpath "$0")
readonly MY_DIR=$(dirname "$MY_PATH")
eval $(cat /etc/os-release | grep ID)

readonly REQUIRED_TOOLS="python3 sudo"
MISSING_TOOLS=""

install_missing_tools() {
  if is_root_user; then
    readonly SUDO=""
  else
    readonly SUDO="sudo -E"
  fi

  case "$ID" in
  debian | ubuntu)
    $SUDO apt-get update
    $SUDO apt-get install -y $MISSING_TOOLS
    ;;
  centos)
    $SUDO yum install -y $MISSING_TOOLS
    ;;
  *)
    echo "Error: $ID is not supported."
    exit 1
    ;;
  esac
}

is_root_user() {
  test $(id -u) = "0"
}

is_missing() {
  ! command -v "$1" >/dev/null
}

for tool in $REQUIRED_TOOLS; do
  if is_missing $tool; then
    echo "Error: cannot find $tool. $tool is required by p4studio CLI to be installed."
    if [ -z "$MISSING_TOOLS" ]; then
      MISSING_TOOLS="$tool"
    else
      MISSING_TOOLS="$MISSING_TOOLS $tool"
    fi
  fi
done

if [ -n "$MISSING_TOOLS" ]; then
  if is_missing "sudo" && ! is_root_user; then
    echo "Error: to install sudo please run p4studio CLI as root or install sudo manually."
    exit 1
  fi

  while true; do
    read -p "Do you want to install $(echo "$MISSING_TOOLS" | sed "s/ / and /")? (Y/n): " answer
    case "$answer" in
    [Yy]* | "")
      install_missing_tools
      break
      ;;
    [Nn]*) exit 1 ;;
    *) echo "Please answer yes or no." ;;
    esac
  done
fi

exec python3 "$MY_DIR" "$@"
