#!/bin/bash

[ -f testing.sh ] && . testing.sh

#testing "name" "command" "result" "infile" "stdin"

CPUS=$(($(nproc)+0))
if [ $CPUS -lt 2 ]
then
  echo "$SHOWSKIP: taskset (not SMP)"
  return 2 > /dev/null
  exit
fi
MASK=$(printf %x $(((1<<CPUS)-1)))
LAST=$(printf %x $((1<<(CPUS-1))))

# pid 0 means the taskset process itself.
testing 'set mask to all' \
  '(taskset $MASK taskset -p 0 | sed "s/.*: //")' "$MASK\n" '' ''
testing 'set mask to first' \
  '(taskset 1 taskset -p 0 | sed "s/.*: //")' '1\n' '' ''
testing 'set mask to last' \
  '(taskset $LAST taskset -p 0 | sed "s/.*: //")' "$LAST\n" '' ''

# alas procps-ng always says "-" for -o cpu so fetch the field from /proc
testing 'run on first' \
  'X=$(taskset 1 cat /proc/self/stat); x() { echo ${39};}; x $X' \
  '0\n' '' ''
testing 'run on last' \
  'X=$(taskset $LAST cat /proc/self/stat); x() { echo ${39};}; x $X' \
  "$((CPUS-1))\n" '' ''

testing "long mask doesn't segfault" \
  'taskset $(printf %99999s | tr \  0)f echo; echo $?' '\n0\n' '' ''
testing "taskset error checking" \
  'taskset 0 echo nope 2>/dev/null; echo $?' '1\n' '' ''
