#!/usr/bin/env sh
set -eu

info() { printf '%s\n' "[INFO] $*"; }
warn() { printf '%s\n' "[WARN] $*" >&2; }
die()  { printf '%s\n' "[ERR ] $*" >&2; exit 1; }

need_cmd() { command -v "$1" >/dev/null 2>&1; }

OS="$(uname -s 2>/dev/null || echo unknown)"

install_pkgs_linux() {
  # Install packages using an available package manager
  if need_cmd apt-get; then
    sudo apt-get update -y
    sudo apt-get install -y "$@"
  elif need_cmd dnf; then
    sudo dnf install -y "$@"
  elif need_cmd yum; then
    sudo yum install -y "$@"
  elif need_cmd pacman; then
    sudo pacman -Sy --noconfirm "$@"
  elif need_cmd apk; then
    sudo apk add --no-cache "$@"
  else
    die "No supported package manager found (apt/dnf/yum/pacman/apk)."
  fi
}

ensure_zsh() {
  if need_cmd zsh; then
    info "zsh: already installed ($(command -v zsh))"
    return 0
  fi

  info "zsh: installing..."
  case "$OS" in
    Darwin)
      if need_cmd brew; then
        brew install zsh
      else
        die "On macOS, Homebrew is required to install zsh (or install zsh manually)."
      fi
      ;;
    Linux)
      install_pkgs_linux zsh
      ;;
    *)
      die "Unsupported OS: $OS"
      ;;
  esac
}

ensure_deps() {
  # git/curl are useful (and starship's installer needs curl)
  case "$OS" in
    Darwin)
      # Usually present on macOS, but install via brew if missing
      if need_cmd brew; then
        need_cmd git  || brew install git
        need_cmd curl || brew install curl
      fi
      ;;
    Linux)
      install_pkgs_linux git curl
      ;;
  esac
}

ensure_starship() {
  if need_cmd starship; then
    info "starship: already installed ($(command -v starship))"
    return 0
  fi

  info "starship: installing..."
  # Use the official installer; -y answers "yes" automatically
  if need_cmd curl; then
    curl -fsSL https://starship.rs/install.sh | sh -s -- -y
  else
    die "curl is not available. Please install curl first."
  fi

  need_cmd starship || die "Failed to install starship."
}

write_starship_toml() {
  CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}"
  mkdir -p "$CONFIG_DIR"
  TOML="$CONFIG_DIR/starship.toml"

  if [ -f "$TOML" ]; then
    ts="$(date +%Y%m%d-%H%M%S 2>/dev/null || echo backup)"
    cp "$TOML" "$TOML.bak.$ts"
    info "Backup created: $TOML -> $TOML.bak.$ts"
  fi

  cat > "$TOML" <<'EOF'
# ---- starship: readable + fast preset ----
add_newline = false
command_timeout = 800

format = """
[┌─](bold green)$directory$git_branch$git_status$git_state$nodejs$python$rust$go$cmd_duration
[└─](bold green)$character"""

right_format = """$time"""

# ----- Basics -----
[character]
success_symbol = "[❯](bold green)"
error_symbol = "[❯](bold red)"
vimcmd_symbol = "❮"

[directory]
read_only = " "
format = "  [$path]($style) "
style = "bg:#2e3440 fg:cyan bold"
truncation_length = 3
truncate_to_repo = true

[cmd_duration]
min_time = 200
format = "   [$duration]($style)"
style = "yellow"

[time]
disabled = false
format = "[$time]($style)"
time_format = "%H:%M"
style = "dimmed white"

# ----- User / host (show only when useful) -----
[username]
show_always = false
format = "[$user]($style) "
style_user = "dimmed white"
style_root = "bold red"

[hostname]
ssh_only = true
format = "[@$hostname]($style) "
style = "dimmed white"

# ----- Git -----
[git_branch]
format = "   [$branch]($style)"
style = "bold purple"

[git_status]
format = " [$all_status$ahead_behind]($style)"
style = "purple"
conflicted = "≠"
ahead = "⇡${count}"
behind = "⇣${count}"
diverged = "⇕⇡${ahead_count}⇣${behind_count}"
untracked = "?${count}"
stashed = "*${count}"
modified = "!${count}"
staged = "+${count}"
renamed = "»${count}"
deleted = "✘${count}"

[git_state]
format = " [$state( $progress_current/$progress_total)]($style)"
style = "dimmed purple"

# ----- Languages (only show when relevant) -----
[nodejs]
format = "   [$version]($style)"
style = "green"
detect_extensions = ["js", "mjs", "cjs", "ts", "mts", "cts"]
detect_files = ["package.json", ".node-version", ".nvmrc", "pnpm-lock.yaml", "yarn.lock"]

[python]
format = "   [$version]($style)"
style = "blue"
detect_files = ["pyproject.toml", "requirements.txt", "Pipfile", "poetry.lock", ".python-version"]
python_binary = ["python3", "python"]

[rust]
format = "   [$version]($style)"
style = "red"
detect_files = ["Cargo.toml"]

[golang]
format = "   [$version]($style)"
style = "cyan"
detect_files = ["go.mod"]

[docker_context]
format = "   [$context]($style)"
style = "blue"
only_with_files = true
detect_files = ["docker-compose.yml", "docker-compose.yaml", "Dockerfile"]

# ----- Reduce noise -----
[package]
disabled = true

[line_break]
disabled = false
EOF

  info "Written: $TOML"
}

ensure_zshrc_starship_init() {
  ZSHRC="$HOME/.zshrc"

  # Create the file to prevent zsh-newuser-install prompt
  [ -f "$ZSHRC" ] || : > "$ZSHRC"

  # Do not append if it's already there
  if grep -q 'starship init zsh' "$ZSHRC" 2>/dev/null; then
    info ".zshrc already contains starship init"
    return 0
  fi

  {
    printf '\n# --- starship ---\n'
    printf 'eval "$(starship init zsh)"\n'
  } >> "$ZSHRC"

  info "Updated: $ZSHRC"
}

try_chsh() {
  # Allow users to opt out
  [ "${SKIP_CHSH:-0}" = "1" ] && { info "SKIP_CHSH=1 set; skipping chsh"; return 0; }

  ZSH_PATH="$(command -v zsh || true)"
  [ -n "$ZSH_PATH" ] || return 0

  # No need to change if already zsh
  current_shell="${SHELL:-}"
  if [ "$current_shell" = "$ZSH_PATH" ]; then
    info "Default shell is already zsh ($ZSH_PATH)"
    return 0
  fi

  info "Changing default shell to: $ZSH_PATH"
  if chsh -s "$ZSH_PATH" >/dev/null 2>&1; then
    info "chsh completed successfully"
  else
    warn "chsh failed (may require permissions or interactive input)"
    warn "Run manually: chsh -s \"$ZSH_PATH\""
  fi
}

main() {
  info "Detected OS: $OS"
  ensure_deps
  ensure_zsh
  ensure_starship
  write_starship_toml
  ensure_zshrc_starship_init
  try_chsh

  sudo rm -rf /etc/update-motd.d/

  printf '\n'
  info "Setup complete."
  info "To apply changes, open a new terminal or log out and log back in."
  info "To try immediately: exec zsh -l"
  echo "logout to apply"
}

main "$@"
