#!/bin/bash
set -e

usage () {
  echo "Usage: $SCRIPTNAME [OPTION]... ID NAME"
}

. ${SYSCONFIG:=/etc/sysconfig}/scripts/hardware/functions

ID=$1
NAME=$2

check_devpath /bus/ccw/devices/$ID
read_config ccw $ID

CCWGROUP_ID=$CCWGROUP_CHANS

if [ "$NAME" == cu3088 ]; then
  modprobe ctcm 2> /dev/null || :
  modprobe ctc 2> /dev/null || :

  if [ -d $SYSFS/module/ctcm ]; then
    DRIVER=ctcm
  elif [ -d $SYSFS/module/ctc ]; then
    DRIVER=ctc
  else
    error "no kernel module for ctc devices available!"
  fi
elif [ "$NAME" == qeth ]; then
  if [ ! -d $SYSFS/bus/ccw/drivers/qeth ]; then
    modprobe qeth 2> /dev/null || :
    if [ ! -d $SYSFS/module/qeth ]; then
      error "no kernel module for qeth devices available!"
    fi
  fi
  DRIVER=qeth
fi

ccw=/bus/ccw/devices/$ID/driver
ccwgroup=/bus/ccwgroup/drivers/$DRIVER

message_n "Configuring device $ID: "
if test -d "$SYSFS$ccwgroup/$CCWGROUP_ID" ; then
  message_n "already configured. "
else
  # Check whether all channels for this device are accessible
  num=0
  for id in "${CCWGROUP_CHANS[@]}"; do
    if ! [ -d "$SYSFS${ccw}/${id}" ]; then
      list=
      break;
    fi
    list="${list:+${list},}${id}"
  done

  # Configure the channel group
  # Note that the non-existence of channels is not a failure;
  # if we were called during start-up it might well be that
  # not all channels are available yet.
  if test -z "$list" ; then
    message "not (yet) available!"
    exit 0
  else
    echo $list > $SYSFS$ccwgroup/group
    message_n "ok. "
  fi
fi

read _online < $SYSFS$ccwgroup/$CCWGROUP_ID/online
if test "$_online" -eq "1" ; then
  message "already online."
  exit 0
fi

write_option () {
  option="$1"
  file="$SYSFS$ccwgroup/$CCWGROUP_ID/$option"
  shift
  found=
  for i in "$@"; do
    [ "$option" = "$i" ] && found=1
  done
  if test $found; then
    message_n "($option) "
    echo 1 > $file
  elif [ -f $file ]; then
    echo 0 > $file
  fi
}

write_setting () {
  if [ "$2" ]; then
    message_n "($1 $2) "
    echo "$2" > $SYSFS$ccwgroup/$CCWGROUP_ID/$1
  fi
}

case $DRIVER in
  ctc|ctcm)
    write_setting "buffer" "$CTC_BUFFER"
    write_setting "protocol" "$CTC_PROTOCOL"
    ;;
  qeth)
    write_setting "portname" "$QETH_PORTNAME"
    write_setting "portno" "$QETH_PORTNO"
    write_option "fake_broadcast" "${QETH_OPTIONS[@]}"
    write_option "fake_ll" "${QETH_OPTIONS[@]}"
    write_option "layer2" "${QETH_OPTIONS[@]}"
    ;;
esac

echo 1 > $SYSFS$ccwgroup/$CCWGROUP_ID/online
message "ok."

