#!/bin/bash
# a script to find a remote ICC profile for a local monitor

if [ "$1" = "-h" ]; then
  echo Usage:
  echo "  $0 short_manufacturer_name model_name"
  echo ""
  exit 0
fi

short_name=$1
model=$2

manufacturers_db="`curl http://icc.opensuse.org/manufacturers`"
echo "$manufacturers_db" > tmp.json
count=`oyjl/oyjl tmp.json -c tmp.json`

echo count of manufacturers in DB: $count
found_manufacturer=-1
i=0
while [ $i -lt $count ]; do
  manufacturer="`oyjl/oyjl tmp.json -x [$i] | grep short_name | sed 's/short_name: //'`"
  let i=i+1
  if [ `echo $manufacturer | grep "$short_name" | wc -l` -ne 0 ]; then
    found_manufacturer=$i
    devices_db="`curl -s http://icc.opensuse.org/devices/$short_name`"
    break
  fi
done

echo "$devices_db" > tmp.json
count=`oyjl/oyjl tmp.json -c tmp.json`
i=0
while [ $i -lt $count ]; do
  device="`oyjl/oyjl tmp.json -x [$i] | grep model | sed 's/model: //'`"
  if [ `echo $device | grep "$model" | wc -l` -ne 0 ]; then
    found_device=$i
    devices_db="`curl -s http://icc.opensuse.org/devices/$short_name`"
    profile="`oyjl/oyjl tmp.json -x [$i]/_id | sed 's/\$oid: //'`"
    break
  fi
  let i=i+1
done

  if [ $found_device -eq -1 ]; then
    echo Could not find the local display in the DB
  else
    let found_manufacturer=found_manufacturer+1
    let found_device=found_device+1
    echo "$found_manufacturer"th manufacturer "$found_device"th device matches
    echo $profile
    echo http://icc.opensuse.org/profile/$profile/0/profile.icc
    curl -s http://icc.opensuse.org/profile/$profile/0/profile.icc -o $short_name-$model.icc
    echo --> $short_name-$model.icc
  fi

