#!/usr/bin/env bash
set -u

# Require root so we can write to /etc/profile.d
if [ "${EUID:-$(id -u)}" -ne 0 ]; then
  echo "This script must be run as root."
  exit 1
fi

# Colors via tput if available, else ANSI; use 256-color orange (214) fallback to yellow
if command -v tput >/dev/null 2>&1; then
  RESET="$(tput sgr0)"
  GREEN="$(tput setaf 2 || true)"
  RED="$(tput setaf 1 || true)"
  if [ "$(tput colors 2>/dev/null || echo 0)" -ge 256 ]; then
    ORANGE="$(printf '\033[38;5;214m')"
  else
    ORANGE="$(tput setaf 3 || printf '\033[33m')"
  fi
else
  RESET=$'\033[0m'
  GREEN=$'\033[32m'
  RED=$'\033[31m'
  ORANGE=$'\033[33m'
fi

info()  { printf "%b%s%b\n" "$ORANGE" "$1" "$RESET"; }
ok()    { printf "%b%s%b\n" "$GREEN" "$1" "$RESET"; }
fail()  { printf "%b%s%b\n" "$RED"   "$1" "$RESET"; }

# 1. Clear screen
clear

# 2. Orange message
info "Customizing LXC Login."

# 3. Write profile snippet (single-quoted heredoc prevents expansion now; runs at login)
target="/etc/profile.d/00_lxc-details.sh"
umask 022
if install -d -m 0755 /etc/profile.d && \
   cat > "$target" <<'EOF'
echo -e ""
echo -e "    🌐  [m[33m Provided by: Ins0mniA[m"
echo ""
echo -e "    🏠  [m[33m Hostname: [1;92m$(hostname)[m"
echo -e "    💡  [m[33m IP Address: [1;92m$(hostname -I | awk '{print $1}')[m"
echo -e ""
EOF
then
  chmod 0644 "$target"
  # 4. Green completion message
  ok "Customizing LXC Login COMPLETED."
  exit 0
else
  fail "Failed writing /etc/profile.d/00_lxc-details.sh"
  exit 1
fi
