#!/bin/sh

set -eux

RESOLVER=lts-16.26
PACKAGES="pandoc lens hledger criterion"
STACK=stack_4UGRPL64YTZHOPDZINL3WB3T6TS47YCNNCRLYWOIDSFI54RO
STACK_URL="https://ro-che.info/tmp/${STACK}"
SLEEP_TIME="2m"
HOSTNAME=$(hostname)
REPLICATES=3
# set CPU_POWER to false when cpupower doesn't work e.g. due to the "Game Boost"
# feature
CPU_POWER=true

if [ "$USER" != bench ]
then
  echo >&2 "Run this under a dedicated user named bench"
  exit 1
fi

# Check if we can run sudo cpupower
if "$CPU_POWER" && ! sudo cpupower frequency-info >/dev/null </dev/null
then
  echo >&2 "Run visudo and add the following line:"
  echo >&2 "bench ALL=(root) NOPASSWD: /bin/cpupower"
  exit 1
fi

cd

if [ ! -x "$STACK" ]; then
  wget -O "$STACK" "$STACK_URL"
  chmod +x "$STACK"
fi

if ! [ -d .stack-base ]
then
  rm -rf .stack
  "./${STACK}" setup --resolver="$RESOLVER"
  "./${STACK}" build --resolver="$RESOLVER" --dry-run --prefetch $PACKAGES
  mv .stack .stack-base
fi

printf "machine,package,real_time,user_time\n" > "times.csv"

for pkg in $PACKAGES all; do
  for i in $(seq 1 "$REPLICATES"); do
    printf "%s\n" "$pkg"
  done
done |
  shuf |
  while read pkg; do
    if [ "$pkg" = all ]
    then
      pkgs_to_build="$PACKAGES"
    else
      pkgs_to_build="$pkg"
    fi

    if "$CPU_POWER"; then
      sudo cpupower frequency-set -g performance >/dev/null
    fi

    rm -rf .stack
    cp -r .stack-base .stack
    time_file=$(mktemp)
    /bin/time --output "$time_file" --format "%e,%U" "./${STACK}" build --resolver="$RESOLVER" $pkgs_to_build >/dev/null 2>&1
    if "$CPU_POWER"; then
      sudo cpupower frequency-set -g powersave >/dev/null
    fi

    times=$(cat "$time_file")
    rm "$time_file"
    printf "%s,%s,%s\n" "$HOSTNAME" "$pkg" "$times" >> "times.csv"

    # https://stackoverflow.com/a/29269811/110081
    simple_time=$( date -d@"${times%,*}" -u "+%H:%M:%S" )

    echo "Finished compiling ${pkg} in ${simple_time}; sleeping for ${SLEEP_TIME} minutes to let the machine cool down"
    sleep "$SLEEP_TIME"
  done
