#!/bin/sh

s390_migrate_collect_to_chzdev() {

	# Convert legacy collect based udev rules for s390x device
	# initialization to the new chzdev based scheme

        [ -f /sbin/chzdev ] || return 0

        for rule in /etc/udev/rules.d/*.rules; do

                # The rule files might contain several occurences of
                # IMPORT{program}="collect ..." but we're interested
                # only in the first occurence, the rest are ignored.

                import_builtin_collect=$(grep --max-count=1 -F 'IMPORT{program}="collect' $rule) ||
                        continue

                echo "Migrating collect based udev rule $rule to new chzdev based scheme..."

                CHANNEL=$(echo $import_builtin_collect | sed -n 's/.*collect \([[:graph:]]*\).*/\1/p')
                if [ -z "$CHANNEL" ]; then
                        echo >&2 "Failed to retrieve CHANNEL info, skipping"
                        continue
                fi

                DEVICE=$(echo $import_builtin_collect | sed -n 's/.* //p')
                DEVICE="${DEVICE%\"}"

                echo "Updating udev rule $rule for device '$DEVICE' channel '$CHANNEL'"

                mv $rule $rule.legacy
                if [ "$DEVICE" == "dasd-eckd" ]; then
                        echo "running: /sbin/chzdev -e -p $DEVICE --no-root-update $CHANNEL"
                        /sbin/chzdev -e -p $DEVICE --no-root-update $CHANNEL
                else
                        GROUP=$(sed -n '/SUBSYSTEM=="ccw"/s/.*group}=" *\([[:graph:]]*\),\([[:graph:]]*\),\([[:graph:]]*\)"/\1:\2:\3/p' $rule.legacy)
                        LAYER2=$(sed -n 's/.*layer2}="\([[:digit:]]\)"/layer2=\1/p' $rule.legacy)
                        PORTNO=$(chzdev --quiet --all $DEVICE --export - | grep portno)
                        echo "running: /sbin/chzdev -e -p $DEVICE --no-root-update ${PORTNO:=portno=0} $LAYER2 $GROUP"
                        /sbin/chzdev -e -p $DEVICE --no-root-update ${PORTNO:=portno=0} $LAYER2 $GROUP
                fi

                if [ $? != 0 ]; then
                        echo >&2 "Warning: Rule conversion failed, restoring original rule!"
                        mv $rule.legacy $rule
                fi
        done
}

s390_migrate_collect_to_chzdev
