#!/usr/bin/env bash

# 1. Detect Architecture
machine=$(uname -m)
if [[ ${machine} == x86_64 ]]; then
  arch=amd64
elif [[ ${machine} == aarch64 ]]; then
  arch=arm64
fi

# 2. Variables & Configuration
APP="brave-browser"
BRANCH="-dev" # Change to "" for release, "-beta" for beta
UBUNTU_CODENAME="stable"
URL="brave-browser-apt${BRANCH}.s3.brave.com"

TYPES=(deb)
URIs="https://${URL}/"
SUITES="${UBUNTU_CODENAME}"
COMPONENTS=(main)
ARCHITECTURES="($arch)"

# Debian standard directory for third-party keys
KEY_DIR="/usr/share/keyrings"
KEY="${KEY_DIR}/brave-browser-archive-keyring.gpg"

# 3. Download Key to /usr/share/keyrings
sudo mkdir -p "${KEY_DIR}"
sudo curl -fsSLo "${KEY}" "https://brave-browser-apt-release.s3.brave.com/brave-browser-archive-keyring.gpg"

# 4. Define deb822 Source Template
conf_print_brave_sources() {
  cat <<EOF
Enabled: yes
Types: ${TYPES[*]}
URIs: ${URIs}
Suites: ${SUITES}
Components: ${COMPONENTS[*]}
Architectures: ${ARCHITECTURES[*]}
Signed-By: ${KEY}
EOF
}

# 5. Deploy Sources File (Available -> Enabled Symlink Pattern)
SOURCES_NAME="${APP}${BRANCH}-${UBUNTU_CODENAME}.sources"

# Ensure available directory exists
sudo mkdir -p /etc/apt/sources.list-available

conf_print_brave_sources | sudo tee "/etc/apt/sources.list-available/${SOURCES_NAME}" >/dev/null

# Create the symlink to enable the repo
sudo ln -sf "/etc/apt/sources.list-available/${SOURCES_NAME}" "/etc/apt/sources.list.d/${SOURCES_NAME}"

# 6. System Updates and Installation
sudo apt update
sudo apt install "${APP}${BRANCH}" -y

# 7. Post-Install Configurations
echo 'kernel.unprivileged_userns_clone=1' | sudo tee /etc/sysctl.d/00-local-userns.conf >/dev/null

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

if [ -f "$PROXY_CONF" ]; then
  if ! grep -q "${URL}" "$PROXY_CONF"; then
    echo "$PROXY_LINE" | sudo tee -a "$PROXY_CONF" >/dev/null
  fi
else
  echo "$PROXY_LINE" | sudo tee "$PROXY_CONF" >/dev/null
fi
