#!/bin/bash

SCRIPTNAME=${0##*/}

CHANDEV_CONF=/etc/chandev.conf
OUTPUT_DIR=

while getopts ":c:ho:" OPT; do
  case "$OPT" in
    c)
    CHANDEV_CONF="$OPTARG"
    ;;
    h)
    usage
    exit $R_SUCCESS
    ;;
    o)
    OUTPUT_DIR="$OPTARG"
    ;;
    :)
    echo "$SCRIPTNAME: option requires an argument -- $OPTARG" >&2
    echo "Try: \`$SCRIPTNAME -h' for mor information." >&2
    exit $R_USAGE
    ;;
    ?)
    echo "$SCRIPTNAME: illegal option -- $OPTARG" >&2
    echo "Try: \`$SCRIPTNAME -h' for mor information." >&2
    exit $R_USAGE
  esac
done

fix_dev () {
  dev=$(echo $1 | tr "[A-F]" "[a-f]")
  dev=0.0.${dev#0x}
  echo $dev
}

orig_IFS="$IFS"

devices=()
params=()

while read in; do
  [ -z "$in" ] && continue
  [ "${in#\#}" != "$in" ] && continue
  IFS=,
  set -- $in
  IFS="$orig_IFS"
  echo got input: $@
  if [ "$1" = "auto" -o "$1" = "noauto" ]; then
    true
  elif [ "$1" = "add_parms" ]; then
    true
  elif [ "${1#ctc}" != "$1" ]; then
    read_dev=$2
    write_dev=$3
    protocol=$6
    echo got ctc: $read_dev $write_dev, protocol: $protocol
    devices+=("ctc $read_dev $write_dev $protocol")
  elif [ "${1#qeth}" != "$1" ]; then
    read_dev=$2
    write_dev=$3
    data_dev=$4
    port=$6
    echo got qeth: $read_dev $write_dev $data_dev, port: $port
    devices+=("qeth $read_dev $write_dev $data_dev $port")
  else
    echo "$SCRIPTNAME: got unparsable input -- $in" >&2
    exit 1
  fi
done < $CHANDEV_CONF

for dev in "${devices[@]}"; do
  set -- $dev
  if [ "$1" = ctc ]; then
    config="config-$(fix_dev $2)"
    dev="($(fix_dev $2) $(fix_dev $3))"
    protocol=$4
    echo $config:
    echo "CCWGROUP_CHANS=$dev"
    [ "$4" ] && echo "CTC_PROTOCOL=$protocol"
  elif [ "$1" = qeth ]; then
    true
  fi
done
