#!/bin/sh -e

# ANSI color codes
RED='\033[0;31m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
LIGHT_GREEN='\033[0;92m'
BOLD='\033[1m'
NC='\033[0m' # No Color

echo_error() {
  printf "${BOLD}${RED}ERROR: ${NC}${RED}%s${NC}\n" "$1" >&2
}

echo_info() {
  printf "${BOLD}${CYAN}INFO: ${NC}${CYAN}%s${NC}\n" "$1"
}

echo_warning() {
  printf "${BOLD}${YELLOW}WARNING: ${NC}${YELLOW}%s${NC}\n" "$1"
}

echo_note() {
  printf "${BOLD}${LIGHT_GREEN}NOTE: ${NC}${LIGHT_GREEN}%s${NC}\n" "$1"
}

# Check if the user is root and set sudo variable if necessary
check_root() {
  if [ "$(id -u)" -ne 0 ]; then
    if command_exists sudo; then
      echo_info "User is not root. Using sudo for privileged operations."
      _sudo="sudo"
    else
      echo_error "No sudo found and you're not root! Can't install packages."
      return 1
    fi
  else
    echo_info "Root access confirmed."
    _sudo=""
  fi
}

# < Distribution detection and installation >
get_packager() {
  if [ -e /etc/os-release ]; then
    echo_info "Detecting distribution..."
    . /etc/os-release

    # < Convert $ID and $ID_LIKE to lowercase >
    ID=$(printf "%s" "$ID" | tr '[:upper:]' '[:lower:]')
    ID_LIKE=$(printf "%s" "$ID_LIKE" | tr '[:upper:]' '[:lower:]')

    case "$ID" in
    ubuntu | pop) _install() {
      $_sudo apt-get install "$@" --assume-yes
    } ;;
    debian) _install() {
      $_sudo apt-get install "$@" --assume-yes
    } ;;
    fedora) _install() {
      $_sudo dnf install "$@" -y
    } ;;
    alpine) _install() {
      $_sudo apk add "$@"
    } ;;
    arch | manjaro | garuda | endeavour) _install() {
      $_sudo pacman -S "$@" --noconfirm
    } ;;
    opensuse*) _install() { $_sudo zypper in "$@" -y; } ;;
    *)
      if [ "${ID_LIKE#*debian}" != "$ID_LIKE" ]; then
        _install() { $_sudo apt-get install "$@" --assume-yes; }
      elif [ "${ID_LIKE#*ubuntu}" != "$ID_LIKE" ]; then
        _install() { $_sudo apt-get install "$@" --assume-yes; }
      elif [ "${ID_LIKE#*arch}" != "$ID_LIKE" ]; then
        _install() { $_sudo pacman -S "$@" --noconfirm; }
      elif [ "${ID_LIKE#*fedora}" != "$ID_LIKE" ]; then
        _install() { $_sudo dnf install "$@" -y; }
      elif [ "${ID_LIKE#*suse}" != "$ID_LIKE" ]; then
        _install() { $_sudo zypper in "$@" -y; }
      else
        echo_error "Unsupported distribution: $ID"
        exit 1
      fi
      ;;
    esac
  else
    echo_error "Unable to detect distribution. /etc/os-release not found."
    exit 1
  fi
}

# Check if a command exists
command_exists() {
  command -v "$@" >/dev/null 2>&1
}

# Install dependencies
_dependencies() {
  tools="git cmake make"
  packages="libuv1-dev libssl-dev libhwloc-dev"

  for tool in $tools; do
    if command_exists "$tool"; then
      echo_note "$tool is already installed"
    else
      echo_info "Installing $tool.."
      _install "$tool" || echo_error "Failed to install $tool"
    fi
  done

  for package in $packages; do
    echo_info "Installing $package"
    _install "$package" || echo_error "Failed to install $package"
  done

  echo_note "Dependency check completed!"
}

# Clone the repository and prepare build directory
_git() {
  xmrig_dir="$HOME/.bin/xmrig"

  if [ -d "$xmrig_dir" ]; then
    echo_warning "$xmrig_dir already exists. Skipping clone."
  else
    echo_info "Cloning xmrig repository to $xmrig_dir"
    mkdir -p "$HOME/.bin"
    if ! git clone --depth=1 https://github.com/xmrig/xmrig.git "$xmrig_dir"; then
      echo_error "Failed to clone xmrig repository."
      return 1
    fi
  fi

  build_dir="$xmrig_dir/build"
  mkdir -p "$build_dir" || {
    echo_error "Failed to create build directory: $build_dir"
    return 1
  }

  cd "$build_dir" || {
    echo_error "Failed to navigate to build directory: $build_dir"
    return 1
  }
}

# Initialize and build the application
_appinit() {
  echo_info "Running cmake .."
  if ! cmake ..; then
    echo_error "CMake failed."
    return 1
  fi

  echo_info "Running make (this could take a while)"
  if ! make; then
    echo_error "Make failed."
    return 1
  fi

  $_sudo ln -s ./xmrig /usr/bin/xmrig || "Link of application failed hard! Is not accessible at /usr/bin/xmrig"
}

# Main function
main() {
  if ! check_root; then
    echo_error "Root check failed. Exiting."
    return 1
  fi

  if ! get_packager; then
    echo_error "Failed to detect distribution or set packager."
    return 1
  fi

  _dependencies || return 1

  if _git; then
    _appinit || echo_error "Build initialization failed."
  else
    echo_error "Failed during Git operations."
  fi
}

main
