#!/bin/bash

DRIVERS=("300_0C00.nal" "1100_0A00.nal" "1300_0C26.nal" "1300i_0D12.nal")

CONFIG=$(cat << EOF
# Fujitsu S300
firmware /usr/share/sane/epjitsu/300_0C00.nal
usb 0x04c5 0x1156

# Fujitsu S1300
firmware /usr/share/sane/epjitsu/1300_0C26.nal
usb 0x04c5 0x11ed

# Fujitsu S1100
firmware /usr/share/sane/epjitsu/1100_0B00.nal
usb 0x04c5 0x1200

# Fujitsu S1300i
firmware /usr/share/sane/epjitsu/1300i_0D12.nal
usb 0x04c5 0x128d
EOF
)

TMP_DIR=$(mktemp -d)
cd $TMP_DIR
sudo mkdir -p /usr/share/sane/epjitsu/
for i in ${DRIVERS[*]}; do
	if [ -f "/usr/share/sane/epjitsu/$i" ]; then
		echo "$i already downloaded"
	else
		wget "https://jkeyne.dev/scanner_drivers/$i"
		sudo cp "$TMP_DIR/$i" "/usr/share/sane/epjitsu/$i"
	fi
done

# grep -q 'Fujitsu S1300i' /etc/sane.d/epjitsu.conf || echo $CONFIG | sudo tee -a /etc/sane.d/epjitsu.conf > /dev/null
conf_file="/etc/sane.d/epjitsu.conf"

if grep -q 'Fujitsu S1300i' $conf_file; then
	echo 'Sane is already configured'
else
	echo 'Installing sane config'
	echo $CONFIG | sudo tee -a $conf_file > /dev/null
fi

