#!/bin/bash
set -evo pipefail

echo "[*] Monero Updating"
echo "[-] Removing old monero binaries..."
rm -rf monero-*-linux-*

echo -e "[*] Checking architecture..."

if [[ $(arch) = "x86_64" ]]; then
	# Download latest 64-bit binaries
	echo "[*] Download latest Linux binaries..."
	wget -q --content-disposition https://downloads.getmonero.org/cli/linux64
elif [[ $(arch) = "aarch64" || $(arch) = "aarm64" || $(arch) = "armv8" ]]; then
	# Download latest armv8 binaries
	echo "[*] Download latest Linux Arm8 binaries..."
	wget -q --content-disposition https://downloads.getmonero.org/cli/linuxarm8
elif [[ $(arch) = "armv71" ]]; then
	# Download latest armv7 binaries
	echo "[*] Download latest Linux Arm7 binaries..."
	wget -q --content-disposition https://downloads.getmonero.org/cli/linuxarm7
else
	echo -e "\e[31m[!] ERROR: Architecture not found.  Please see https://www.getmonero.org/downloads/ to download manually.\e[0m"
	exit 1
fi

# Verify shasum of downloaded binaries
echo "[*] Verifying hashes of downloaded binaries..."
if shasum -a 256 -c hashes.txt -s --ignore-missing
then
        echo
        echo "[~] Success: The downloaded binaries verified properly!"
else
        echo
        echo -e "\e[31m[!] DANGER: The download binaries have been tampered with or corrupted.\e[0m"
        rm -rf monero-linux-*.tar.bz2
        exit 1
fi

echo "[~] Extracting new monero binaries..."
tar xvf monero-linux-*.tar.bz2
rm monero-linux-*.tar.bz2

echo "[-] Stopping monerod..."
sudo systemctl stop monerod

echo "[~] Copying binaries to /usr/local/bin/"
sudo cp -r monero-*-linux-*/* /usr/local/bin/
sudo chown -R monero:monero /usr/local/bin/monero*

echo "[+] Starting monerod..."
sudo systemctl start monerod
