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

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

UBUNTU_CODENAME=bionic
URL="brave-browser-apt-release.s3.brave.com"

#curl -s https://${URL}/brave-core.asc | apt-key --keyring /etc/apt/trusted.gpg.d/brave-browser-release.gpg add -

#sudo curl -fsSLo /usr/share/keyrings/brave-browser-archive-keyring.gpg https://brave-browser-apt-release.s3.brave4u7jddbv7cyviptqjc7jusxh72uik7zt6adtckl5f4nwy2v72qd.onion/brave-browser-archive-keyring.gpg

sudo curl -fsSLo /usr/share/keyrings/brave-browser-archive-keyring.gpg https://brave-browser-apt-release.s3.brave.com/brave-browser-archive-keyring.gpg

sudo echo "deb [signed-by=/usr/share/keyrings/brave-browser-archive-keyring.gpg arch=${arch}] https://${URL} ${UBUNTU_CODENAME} main" | tee /etc/apt/sources.list-available/brave-browser.list

ln -sf /etc/apt/sources.list-available/brave-browser.list /etc/apt/sources.list.d/brave-browser.list

apt update

apt install -y brave-browser brave-keyring

echo 'kernel.unprivileged_userns_clone=1' > /etc/sysctl.d/00-local-userns.conf
#service procps restart

# Bypass apt-proxy for brave packages
# if 02proxy exists check to see if the url is already in it, if so do nothing , if it isn't add it, 
# if 02proxy doesn't exist create it. successful grep 0, unsuccessful 1
if [ -f /etc/apt/apt.conf.d/02proxy ]; then
	echo "02proxy contains: "
	cat /etc/apt/apt.conf.d/02proxy
	if [ ! -z $(grep ${URL} /etc/apt/apt.conf.d/02proxy) ]; then
		echo "first"
		echo "Acquire::http::Proxy { \"${URL}\" DIRECT; };" >> /etc/apt/apt.conf.d/02proxy
	fi
else
	echo "second"
	echo "Acquire::http::Proxy { \"${URL}\" DIRECT; };" >> /etc/apt/apt.conf.d/02proxy
fi
