#!/bin/bash

get_usb_device() {
    local usb_devices=$(lpinfo -v | grep usb |grep $1)
    if [ -z "$usb_devices" ]; then
        echo "No USB devices found."
        return 1
    fi
    local usb_device=$(echo "$usb_devices" | head -n 1 | awk '{print $2}')
    echo "$usb_device"
}

get_printer_driver() {
    local printer_name="$1"
    local drivers=$(lpinfo -m | grep -i "$printer_name")
    if [ -z "$drivers" ]; then
        drivers=$(grep -rn "$printer_name" /usr/share/cups/model |grep "Product" | sed 's|^/usr/share/cups/model/||'|awk -F: '{print $1}')
    fi
    local drivers=$(echo "$drivers" | head -n 1 | awk '{print $1}')
    echo "$drivers"
}

is_printer_exists() {
    local printer_name=$(echo $1 | sed 's/ /_/g')
    local printers=$(lpstat -p | awk '{print $2}')
    if echo "$printers" | grep -q "^$printer_name$"; then
        echo "Printer '$printer_name' already exists."
        return 0
    else
        return 1
    fi
}

setup_printer() {
    local printer_name="$1"
    local printer_serial=$2
    if [ -z "$printer_name" ]; then
        echo "Usage: setup_printer <printer_name>"
        return 1
    fi

    if is_printer_exists "$printer_name"; then
        return 1
    fi

    local usb_device=$(get_usb_device "$printer_serial")
    if [ $? -ne 0 ]; then
        return 1
    fi

    local printer_driver=$(get_printer_driver "$printer_name")
    if [ $? -ne 0 ]; then
        return 1
    fi

    local lpadmin_command="lpadmin -p $(echo $printer_name | sed 's/ /_/g') -E -v $usb_device -m $printer_driver"
    echo "Executing lpadmin command: $lpadmin_command"
    eval "$lpadmin_command"
}

setup_printer "$1" "$2"
