#!/usr/bin/env bash
#
# install-chrome.sh — Native Google Chrome Installer for Ubuntu/Debian
# Downloads and installs the latest official stable release without Snap.
#
# Usage:
#   sudo ./install-chrome.sh

set -euo pipefail
IFS=$'\n\t'

# Ensure the script is run as root
if (( EUID != 0 )); then
  echo "[ERROR] This script must be run as root (via sudo)." >&2
  exit 1
fi

echo "[1/4] Installing necessary prerequisites..."
apt-get update -y
apt-get install -y curl gnupg2 ca-certificates

echo "[2/4] Setting up Google's official repository keys..."
# Create directory for Third-Party APT keys if it doesn't exist
install -d -m 0755 /etc/apt/keyrings

# Fetch the official signing key and save it securely
curl -fsSL https://dl.google.com/linux/linux_signing_key.pub | \
  gpg --dearmor --yes -o /etc/apt/keyrings/google-chrome.gpg

# Configure the APT repository to strictly use that signing key
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/google-chrome.gpg] http://dl.google.com/linux/chrome/deb/ stable main" \
  > /etc/apt/sources.list.d/google-chrome.list

echo "[3/4] Fetching package lists and installing Google Chrome..."
apt-get update -y
apt-get install -y google-chrome-stable

echo "[4/4] Verifying installation..."
if command -v google-chrome &>/dev/null; then
  echo "------------------------------------------------------"
  echo "SUCCESS: Google Chrome has been installed successfully!"
  echo "Version: $(google-chrome --version)"
  echo "------------------------------------------------------"
else
  echo "[ERROR] Google Chrome installation could not be verified." >&2
  exit 1
fi