#!/usr/bin/env bash

set -e

# Ensure $HOME exists
if [ -z "$HOME" ]; then
	echo "❌ HOME variable not set!"
	exit 1
fi

if [ "$EUID" -eq 0 ]; then
	# Already root → no prompt needed
	echo "ℹ️  Script is running as root."
	ICONS_DIR="/usr/share/icons/ProtonAG"
	echo "ℹ️  Installing system-wide ($ICONS_DIR)"

else
	echo "ℹ️  Script is running as user."
	echo
	read -r -p "Install as 'root' or 'user'? [Default = user]: " INSTALL_LOCATION
	echo

	if [ "$INSTALL_LOCATION" = "root" ]; then
		echo "❌ Root install selected, but script is not running as root."
		echo
		echo "ℹ️  Please re-run the script as root:"
		echo
		echo "  sudo bash $0"
		echo
		echo "or:"
		echo
		echo "  su -"
		echo "  <password>"
		echo "  bash $0"
		echo
		exit 1
	fi

	ICONS_DIR="$HOME/.local/share/icons/ProtonAG"
	echo "ℹ️  Installing as user ($ICONS_DIR)"
fi

# Make icons folder
echo
echo "ℹ️  Creating directory..."
if ! mkdir -p "$ICONS_DIR"; then
	echo "❌ Failed to create directory $ICONS_DIR!"
	exit 1
fi
echo "✅ Successfully created directory!"
echo

[ -w "$ICONS_DIR" ] && [ -x "$ICONS_DIR" ] || {
	echo "❌ No write and/or execute permission to $ICONS_DIR"
	exit 1
}

# Grab Proton SVG files
echo "ℹ️  Downloading Proton icons..."

pids=()
FAILED=0

while IFS= read -r file_url; do
	[ -z "$file_url" ] && continue
	filename="${file_url%%=*}"
	url="${file_url#*=}"
	(
		if ! wget -qO "$ICONS_DIR/$filename" "$url" 2>/dev/null; then
			echo "❌ Failed to download $filename (permission denied or write error)"
			exit 1
		fi
	) &
	pids+=($!)
done <"./links/1.txt"
# ^links2.txt and links3.txt have some extra stuff. Feel free to use that.

for pid in "${pids[@]}"; do
	if ! wait "$pid"; then
		FAILED=1
	fi
done

if [ "$FAILED" -ne 0 ]; then
	echo
	echo "❌ One or more icons failed to download."
	exit 1
fi

echo "✅ All Proton icons downloaded."
