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

# 1. Architecture Detection
machine=$(uname -m)
if [[ ${machine} == "x86_64" ]]; then
  ARCH="amd64"
elif [[ ${machine} == "aarch64" ]]; then
  ARCH="arm64"
else
  echo "Unsupported architecture: ${machine}"
  exit 1
fi

# 2. Configuration
APP="brave-browser"
UBUNTU_CODENAME="stable"
URL="brave-browser-apt-release.s3.brave.com"

# DEB822 Specific Fields
TYPES="deb"
URIs="https://${URL}/"
SUITES="${UBUNTU_CODENAME}"
COMPONENTS="main"

# Directory for modern GPG keyrings (Security Best Practice)
KEY_DIR="/usr/share/keyrings"
KEY_NAME="${APP}-archive-keyring.gpg"
KEY="${KEY_DIR}/${KEY_NAME}"

# Note: DEB822 files MUST use the .sources extension
SOURCES_NAME="${APP}.sources"

# 3. Ensure directories exist
sudo mkdir -p "${KEY_DIR}"
sudo mkdir -p /etc/apt/sources.list-available

# 4. Fetch GPG Key
sudo curl -fsSLo "${KEY}" "https://${URL}/${KEY_NAME}"

# 5. Define DEB822 Source Template
conf_print_brave_sources() {
  cat <<EOF
Enabled: yes
Types: ${TYPES}
URIs: ${URIs}
Suites: ${SUITES}
Components: ${COMPONENTS}
Architectures: ${ARCH}
Signed-By: ${KEY}
EOF
}

# 6. Deploy Sources File (Available)
conf_print_brave_sources | sudo tee "/etc/apt/sources.list-available/${SOURCES_NAME}" >/dev/null

# 7. Enable via Symlink
sudo ln -sf "/etc/apt/sources.list-available/${SOURCES_NAME}" "/etc/apt/sources.list.d/${SOURCES_NAME}"

# 8. Update and Install
sudo apt update
sudo apt install "${APP}" -y

# 9. System Hardening / Sandbox Fix
echo 'kernel.unprivileged_userns_clone=1' | sudo tee /etc/sysctl.d/00-local-userns.conf >/dev/null
sudo sysctl -p /etc/sysctl.d/00-local-userns.conf >/dev/null

# 10. Bypass apt-proxy for Brave repo
PROXY_CONF="/etc/apt/apt.conf.d/02proxy"
PROXY_LINE="Acquire::https::Proxy { \"${URL}\" DIRECT; };"

if [ -f "$PROXY_CONF" ]; then
  # If file exists, only append if the URL isn't already handled
  if ! grep -q "${URL}" "$PROXY_CONF"; then
    echo "$PROXY_LINE" | sudo tee -a "$PROXY_CONF" >/dev/null
  fi
else
  # Create file if it doesn't exist
  echo "$PROXY_LINE" | sudo tee "$PROXY_CONF" >/dev/null
fi
