#!/bin/sh

rm -f cpucycles.o cpucycles.h

(
  echo amd64tscfreq
  echo amd64cpuinfo
  echo x86tscfreq
  echo x86cpuinfo
  echo x86estimate
  echo ia64cpuinfo
  echo powerpclinux
  echo powerpcmacos
  echo powerpcaix
  echo sparcpsrinfo
  echo sparcestimate
  echo sparc32psrinfo
  echo hppapstat
  echo alpha
  echo clockmonotonic
  echo gettimeofday
) | (
  while read n
  do
    okcompilers | (
      while read c cpp options
      do
        echo "=== `date` === Trying $n.c with $c $options..." >&2
        rm -f test cpucycles-impl.o cpucycles-impl.h cpucycles-impl.c
        cp $n.c cpucycles-impl.c || continue
        cp $n.h cpucycles-impl.h || continue
        $c $options -c cpucycles-impl.c || continue
        $c $options -o test test.c cpucycles-impl.o || continue
        ./test || continue
        echo "=== `date` === Success. Using $n.c." >&2
        mv cpucycles-impl.o cpucycles.o
        mv cpucycles-impl.h cpucycles.h
        exit 0
      done
      exit 111
    ) && exit 0
  done
  exit 111
) || (
  echo ===== Giving up. >&2
  rm -f test cpucycles-impl.o cpucycles-impl.h cpucycles-impl.c
  exit 111
) || exit 111
