#!/bin/bash
unset LANG
unset ${!LC_*}
echo "$0 starting" >&2
xenstore-watch cpu | while read
do
  : xenstore event: ${REPLY}
  case "${REPLY}" in
    cpu)
      : just started
      ;;
    cpu/[0-9]/availability|cpu/[0-9][0-9]/availability)
      vcpu="${REPLY%/*}"
      vcpu="${vcpu#*/}"
      sysfs="/sys/devices/system/cpu/cpu${vcpu}/online"
      if test -f "${sysfs}"
      then
        availability="`xenstore-read \"${REPLY}\"`"
        case "${availability}" in
          online|offline)
            if test "${availability}" = "online"
            then
              new_sysfs_state=1
            else
              new_sysfs_state=0
            fi
            read cur_sysfs_state rest < "${sysfs}"
            if test "${cur_sysfs_state}" = "${new_sysfs_state}"
            then
              : the vcpu "${vcpu}" already has state "${availability}" via "${sysfs}"
            else
              : setting vcpu "${vcpu}" to "${availability}" via "${sysfs}"
              echo "setting vcpu ${vcpu} to ${availability}" >&2
              echo "${new_sysfs_state}" > "${sysfs}"
            fi
          ;;
        esac
      fi
    ;;
    *)
      : unhandled
    ;;
  esac
done
exit 1
