#!/usr/bin/env ysh
# YSH syntax demo

use $LIB_YSH/math.ysh --pick min max

assert [-5 === min(0, -5)]

func abs(x) {
  return (x if x > 0 else -x)
}

assert [42 === abs(-42)]

proc read-write (prefix; ; offset=1) {
  json read (&message) < $prefix.json

  var next = message.counts[0] + offset
  echo "Writing new message with $next"

  var new = {next}
  json write (new) > $[prefix]_v2.json
}

proc demo {
  var prefix = '_tmp/foo'

  echo r'''
  {
    "counts": [
      42, 99
    ]
  }
  ''' > $prefix.json

  read-write $prefix (offset=99)
  echo

  head $prefix*.json
}

#
# $0 Dispatch Pattern
#

proc make-jobs {
  for line in (io.stdin) {
    # 150 ms minimum
    var milliseconds = max(line, 150)
    var seconds = milliseconds / 1000
    echo "$seconds"
  }
}

proc do-one (seconds) {
  echo "sleep $seconds"
  sleep $seconds
}

proc do-all {
  ... time
      seq 100 40 300  # 100 milliseconds to 300, by increments of 30
    | make-jobs
    #| xargs -n 1 echo
    | xargs -n 1 -P 3 --verbose -- $0 do-one
    ;
}

if is-main {
  runproc @ARGV
}