#!/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'

# Initialize storage variables
_STORED_ERRORS=""
_STORED_WARNINGS=""
_STORED_INFOS=""
_STORED_NOTES=""

# Modified echo functions that store and display messages
echo_error() {
  message="${RED}$1${NC}\n"
  printf "$message" >&2
  _STORED_ERRORS="${_STORED_ERRORS}${message}"
}

echo_warning() {
  message="${YELLOW}$1${NC}\n"
  printf "$message"
  _STORED_WARNINGS="${_STORED_WARNINGS}${message}"
}

echo_info() {
  message="${CYAN}$1${NC}\n"
  printf "$message"
  _STORED_INFOS="${_STORED_INFOS}${message}"
}

echo_note() {
  message="${LIGHT_GREEN}$1${NC}\n"
  printf "$message"
  _STORED_NOTES="${_STORED_NOTES}${message}"
}

echo_db() {
  message="${LIGHT_GREEN}$1${NC}\n"
  printf "$message"
}

# ─< Check if the given command exists silently >─────────────────────────────────────────
command_exists() {
  command -v "$@" >/dev/null 2>&1
}

# ─< to get the alias to install everything either with your shell or inside your script! >─
if command_exists curl; then
  install_pkg() {
    sh -c "$(curl -sSL https://git.k4li.de/pika/scripts/raw/branch/main/bash/snippets/install_pkg.sh)" -- "$@"
  }
else
  echo_error "curl is not installed, universal install disabled!"
fi

# 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
}

comment_cd_sources() {
  # Path to sources.list
  sources_file="/etc/apt/sources.list"

  # Check if file exists
  if [ ! -f "$sources_file" ]; then
    echo_error "Error: $sources_file not found"
    return 1
  fi

  # Comment out CD-ROM entries using sudo
  $_sudo sed -i 's/^[[:space:]]*deb[[:space:]]\+cdrom:/#&/' "$sources_file"
  echo_info "CD-ROM entries have been commented out in $sources_file"
}

i_yazi() {
  if command_exists curl; then
    curl -fsSL https://git.k4li.de/pika/scripts/raw/branch/main/bash/installs/yazi.sh | sh
  else
    echo_error "No curl was found"
  fi
}

deps="zsh tmux gdu rsync fzf unzip go btop make stow git npm bc pv zoxide ripgrep trash-cli"

check_nala() {
  deb_pkger=""
  echo_info "Updating sources.."
  if ! $_sudo apt-get update; then
    echo_error "Maybe you need a proxy?"
  fi
  if ! command_exists sudo; then
    echo_note "Installing sudo"
    apt-get install sudo --assume-yes
  fi
  if command_exists nala; then
    deb_pkger="nala"
    echo_info "Nala is already present, fetching mirros now! (This might take a minute or two, depending on your internet speed)"
    $_sudo nala fetch --auto --assume-yes
  else
    echo_note "Nala is not installed on the system, do you want to install it now? (Y/n): "
    read -r inst_nala
    case "$inst_nala" in
    N | n)
      deb_pkger="apt-get"
      echo_warning "All right, continue without nala!"
      ;;
    *)
      echo_note "Installing nala.."
      $_sudo apt-get install nala --assume-yes &&
        deb_pkger="nala"

      echo_info "Fetching best mirrors"
      $_sudo nala fetch --auto --assume-yes
      ;;
    esac
  fi
}

inst_debian() {
  comment_cd_sources
  check_nala
  if command_exists nano; then
    if command_exists vi; then
      echo_note "Removing nano"
      $_sudo $deb_pkger remove nano --assume-yes
    else
      echo_info "Removing nano and installing vi as a backup"
      $_sudo $deb_pkger remove nano --assume-yes && $_sudo apt-get install vi --assume-yes
    fi
  fi

  echo_note "Installing base packages: $deps"
  for _deps in $deps; do
    if ! command_exists "$_deps"; then
      if ! $_sudo $deb_pkger install "$_deps" --assume-yes; then
        echo_error "$_deps - failed to install"
      fi
    else
      echo_note "$_deps - was already installed"
    fi
  done

  i_yazi
}

inst_ubuntu() {
  comment_cd_sources
  check_nala
  if command_exists nano; then
    if command_exists vi; then
      echo_note "Removing nano"
      $_sudo $deb_pkger remove nano --assume-yes
    else
      echo_note "Removing nano and installing vi as a backup"
      $_sudo $deb_pkger remove nano --assume-yes && $_sudo apt-get install vi --assume-yes
    fi
  fi

  echo_note "Installing base packages: $deps"
  for _deps in $deps; do
    if ! command_exists "$_deps"; then
      if ! $_sudo $deb_pkger install "$_deps" --assume-yes; then
        echo_error "$_deps - failed to install"
      fi
    else
      echo_note "$_deps - was already installed"
    fi
  done

  i_yazi
}

inst_fedora() {
  if command_exists nano; then
    if command_exists vi; then
      echo_note "Removing nano"
      $_sudo dnf remove nano </dev/tty
    else
      echo_note "Removing nano and installing vi as a backup"
      $_sudo dnf remove nano </dev/tty &&
        $_sudo dnf install vi </dev/tty
    fi
  fi

  echo_note "Installing base packages: $deps"
  for _deps in $deps; do
    if ! command_exists "$_deps"; then
      if ! $_sudo dnf install "$_deps" </dev/tty; then
        echo_error "$_deps - failed to install"
      fi
    else
      echo_note "$_deps - was already installed"
    fi
  done

  i_yazi
}

inst_opensuse() {
  if command_exists nano; then
    if command_exists vi; then
      echo_note "Removing nano"
      $_sudo zypper install -y nano </dev/tty
    else
      echo_note "Removing nano and installing vi as a backup"
      $_sudo zypper install -y vi </dev/tty
    fi
  fi

  echo_note "Installing base packages: $deps"
  for _deps in $deps; do
    if ! command_exists "$_deps"; then
      if ! $_sudo zypper in -y "$_deps" </dev/tty; then
        echo_error "$_deps - failed to install"
      fi
    else
      echo_note "$_deps - was already installed"
    fi
  done

  i_yazi
}

inst_arch() {
  if command_exists nano; then
    if command_exists vi; then
      echo_note "Removing nano"
      $_sudo pacman -R nano --noconfirm
    else
      echo_note "Removing nano and installing vi as a backup"
      $_sudo pacman -S vi --noconfirm
    fi
  fi

  $_sudo pacman -S base-devel --noconfirm
  echo_note "Installing base packages: $deps"
  for _deps in $deps; do
    if ! command_exists "$_deps"; then
      if ! $_sudo pacman -S "$_deps" --noconfirm; then
        echo_error "$_deps - failed to install"
      fi
    else
      echo_note "$_deps - was already installed"
    fi
  done

  i_yazi
}

# ─< 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 | zorin) inst_ubuntu ;;
    debian) inst_debian ;;
    fedora) inst_fedora ;;
    alpine) inst_alpine ;;
    arch | manjaro | garuda | endeavour) inst_arch ;;
    opensuse*) inst_opensuse ;;
    *)
      # Use standard [ ] syntax for string matching
      if [ "${ID_LIKE#*debian}" != "$ID_LIKE" ]; then
        inst_debian
      elif [ "${ID_LIKE#*ubuntu}" != "$ID_LIKE" ]; then
        inst_ubuntu
      elif [ "${ID_LIKE#*arch}" != "$ID_LIKE" ]; then
        inst_arch
      elif [ "${ID_LIKE#*fedora}" != "$ID_LIKE" ]; then
        inst_fedora
      elif [ "${ID_LIKE#*suse}" != "$ID_LIKE" ]; then
        inst_opensuse
      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
}

# Improved display function that only shows categories with content
display_stored_messages() {
  has_messages=0

  # First check if we have any messages at all
  if [ -z "$_STORED_ERRORS" ] && [ -z "$_STORED_WARNINGS" ] && [ -z "$_STORED_INFOS" ] && [ -z "$_STORED_NOTES" ]; then
    return 0
  fi

  # Now display each non-empty category with proper spacing
  if [ -n "$_STORED_ERRORS" ]; then
    printf "\n${BOLD}${RED}=== Errors ===${NC}\n"
    printf "$_STORED_ERRORS"
    has_messages=1
  fi

  if [ -n "$_STORED_WARNINGS" ]; then
    [ "$has_messages" -eq 1 ] && printf "\n"
    printf "${BOLD}${YELLOW}=== Warnings ===${NC}\n"
    printf "$_STORED_WARNINGS"
    has_messages=1
  fi

  if [ -n "$_STORED_INFOS" ]; then
    [ "$has_messages" -eq 1 ] && printf "\n"
    printf "${BOLD}${CYAN}=== Info ===${NC}\n"
    printf "$_STORED_INFOS"
    has_messages=1
  fi

  if [ -n "$_STORED_NOTES" ]; then
    [ "$has_messages" -eq 1 ] && printf "\n"
    printf "${BOLD}${LIGHT_GREEN}=== Notes ===${NC}\n"
    printf "$_STORED_NOTES"
  fi
}

_inst_docker() {
  if ! command_exists docker; then
    bash --norc -c "$(curl -fsSL https://git.k4li.de/pika/scripts/raw/branch/main/bash/installs/docker.sh)"
  else
    echo_note "Docker is already installed, do you need to activate it and make the group changes for $(whoami)? (y/n): "
    read -r _docker
    case "$_docker" in
    N | n)
      return 1
      ;;
    *)
      $_sudo systemctl enable --now docker &&
        $_sudo usermod -aG docker "$(whoami)"
      echo_info "Docker was configured"
      ;;
    esac
  fi
}

_inst_lazydocker() {
  if [ ! -e "$HOME/.local/bin/lazydocker" ]; then
    if command_exists curl; then
      curl https://raw.githubusercontent.com/jesseduffield/lazydocker/master/scripts/install_update_linux.sh | bash
    else
      echo_error "curl is not installed, cannot continue!"
      exit 1
    fi
  else
    echo_warning "$HOME/.local/bin/lazydocker is already present."
  fi
  _dashboard
}

_check_gitpath() {
  if [ ! -d "$HOME/git/" ]; then
    mkdir $HOME/git
  else
    echo_note "git dir is already present"
  fi
}

_ytgo() {
  if ! command_exists go; then
    if ! install_pkg golang; then
      echo_error "Something went wrong, couldn't install golang"
    fi
  fi

  if ! command_exists ytgo; then
    cd "$(mktemp --dir)"
    git clone --depth=1 https://git.k4li.de/pika/ytgo.git
    cd ytgo
    make install
  else
    echo_info "ytgo is already present at $(whereis ytgo)"
  fi
}

_init_dotfiles() {
  _check_gitpath
  echo_db "What dotfiles do you want to clone?
  1. homelab-dotfiles
  2. hyprdots
  3. tty-dotfiles
  q. Quit"
  read -r _dotfiles_db
  case "$_dotfiles_db" in
  1)
    git clone --recursive --depth=1 https://git.k4li.de/dotfiles/homelab-dotfiles.git $HOME/git/homelab-dotfiles
    ;;
  2)
    git clone --recursive --depth=1 https://git.k4li.de/dotfiles/hyprdots.git $HOME/git/hyprdots
    ;;
  3)
    git clone --recursive --depth=1 https://git.k4li.de/dotfiles/tty-dotfiles.git $HOME/git/tty-dotfiles
    ;;
  q)
    return 1
    ;;
  *)
    echo default
    ;;
  esac
  _dashboard
}

_dashboard() {
  echo_db "What else can I do for you?
  1. Docker installation
  2. Dotfile initialization
  3. lazydocker installation
  4. ytgo
  q. Quit"
  read -r _db </dev/tty
  case "$_db" in
  1)
    _inst_docker
    ;;
  2)
    _init_dotfiles
    ;;
  3)
    _inst_lazydocker
    ;;
  4)
    _ytgo
    ;;
  q)
    exit 1
    ;;
  esac
}

main() {
  # set -x
  if check_root; then
    get_packager
    _dashboard
  fi
}

main
