#!/bin/bash
# Configuration section: in principle, these should be filled in by configure
# for now you'll have to give the path to the emc2.1 emc.nml
EMC_NML=/etc/emc2/sample-configs/sim/emc.nml

if ! [ -f $1 ]; then
    q=$(basename $0)
    echo "$q: Update emc 2.0 configuration files for emc2.1"
    echo "Release 2"
    echo 
    echo "Usage: $q path/to/inifile.ini"
    exit 1
fi

DIR=$(cd $(dirname $1); pwd)
NEW=~/emc2.1/configs/$(basename $DIR)
mkdir -p $(dirname $NEW)
cp -a $DIR $NEW
cd $NEW || exit
ini=$(basename $1)

echo "Updating $DIR/$ini -- new configuration saved in $NEW"

# 1: update emc.nml
# md5sum of old emc.nml is 57bfc985dae392b1a1d93e7248c259ac  emc.nml
set -- $(md5sum emc.nml)
if [ "$1" == 57bfc985dae392b1a1d93e7248c259ac ]; then
    cp $EMC_NML .
else
    echo "Old emc.nml was modified; you must update it by hand"
fi

# 2: kinematics
# load "kinematics.hal" as the first hal file.
echo "loadrt trivkins" > kinematics.hal
for i in *.ini; do
awk '/^\[HAL\]/ { print; print "HALFILE = kinematics.hal"; next; } // { print; }'\
     < $i > $i.new && mv -f $i.new $i

# 3: spindle control: replace iocontrol.0 with motion for certain
# spindle-related pins
for i in *.hal; do
    perl -pi.bak -e 's/iocontrol.0.(spindle-(brake|forward|on|reverse|revs|speed-out|sync))/motion.\1/' $i && rm -f $i.new
done

# 4: halcmd "loadusr -W"
# Warn the user if sleep is used in hal files
if grep -q sleep *.hal; then
    cat <<EOF
Your hal files use "sleep".  Sleep should probably be replaced with the use
of 'loadusr -W' in most cases, but this must be done manually.
EOF
fi

# 5: inifile units
# no action is taken because this is not an incompatible change

# 6: halcmd "loadrt blocks"
# no action is taken because this is only a warning in emc2.1

# 7: elimiation of "period" from most components
# this is expected to affect few users, so no action is taken

# 8: elimination of HAL types
for i in *.hal; do
    if egrep -q 'newsig.*[us](8|16)' $i; then
	perl -pi.bak -e 'if(/newsig/) { s/([us])(8|16)/\132/; }' $i && rm $i.bak
    fi
done

# 9: hal_ppmc uses ns units for several pins
for i in *.hal; do
    if egrep -q 'setup-time|pulse-width|pulse-space' $i; then
	perl -pi.bak -e 's/(setp ppmc.[-0-9a-z.]*.(setup-time|pulse-width|pulse-space)) (\d+)/\1-ns ${3}00/' $i && rm $i.bak
    fi
done
