#!/bin/bash

driverContainerName="v10sp1Driver"
ip_address=$(sudo docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $driverContainerName)

setup_printer() {
    local printer_name=$1
    local printer_serial=$2
    local printer_display=$(echo $printer_name | sed 's/ /_/g')

    if [ -z "$printer_name" ]; then
        echo "No printer found."
        return 1
    fi

    sudo docker exec -t -u root $driverContainerName /bin/bash -c "/bin/bash /usr/bin/setup_printer.sh '$printer_name' '$printer_serial'"
    # 等待打印机广播出来，不然ippfind找不到打印机
    echo "waiting for printer to broadcast......."
    sleep 10
    local ipp_address=$(ippfind | grep $printer_display | head -n 1)
    local ipp_address=$(echo $ipp_address | sed "s/ipp:\/\/[^:]*:/ipp:\/\/$ip_address:/g")
    echo "execute lpadmin command: lpadmin -p $printer_display -v $ipp_address -E -m everywhere"
    sudo lpadmin -p $printer_display -v $ipp_address -E -m everywhere
}

get_printer_name() {
    lsusb_ids=$(lsusb | awk '{print $6}')
    for id in $lsusb_ids; do
        is_printer=$(lsusb -v -d $id 2>>/dev/null| grep -i "7 Printer")
        if [ -z "$is_printer" ]; then
            continue
        fi
        device_product=$(lsusb -v -d $id | grep -i "iProduct" | awk '{print substr($0, index($0, $3))}') 
        device_serial=$(lsusb -v -d $id | grep -i "iSerial" | awk '{print substr($0, index($0, $3))}')
        echo "setup printer $device_product $device_serial"
        setup_printer "$device_product" "$device_serial"
    done
}

get_printer_name
