{% set interface = slapparameter_dict.get('interface', 'eth0') -%}
{% set ip = slapparameter_dict.get('ip', '') -%}
{% set gpio_direction_pin = slapparameter_dict.get('gpio-direction-pin', '192') -%}
{% set gpio_pulse_pin = slapparameter_dict.get('gpio-pulse-pin', '193') -%}

[buildout]
parts =
  gpio_setup
  ptp4l-launcher-{{ interface }}
  tsn-script
  publish-connection-information

[directory]
recipe = slapos.cookbook:mkdirectory
etc = $${buildout:directory}/etc
scripts = $${:etc}/tsn

[gpio_setup]
recipe = slapos.recipe.build
gpio-direction-pin = {{ gpio_direction_pin }}
gpio-pulse-pin = {{ gpio_pulse_pin }}
init =
  import os
  def setup_gpio(pin_number):
    gpio_dir = "/sys/class/gpio/gpio" + pin_number
    if not os.path.exists(gpio_dir):
      with open("/sys/class/gpio/export", "w") as fd:
        fd.write(pin_number)
    with open(os.path.join(gpio_dir, "direction"), "w") as fd:
      fd.write("out")
    with open(os.path.join(gpio_dir, "value"), "w") as fd:
      fd.write("0")
  setup_gpio(options["gpio-direction-pin"])
  setup_gpio(options["gpio-pulse-pin"])

[tsn-script-template]
recipe  = slapos.recipe.template:jinja2
rendered= $${directory:scripts}/$${:_buildout_section_name_}
mode    = 755

[ptp4l-launcher-{{ interface }}]
<= tsn-script-template
template= inline:
  #!/bin/sh
  exec {{ chrt }} -f 97 ${linuxptp:location}/sbin/ptp4l -s -S -i {{ interface }} --step_threshold=1 -m

[tsn-script]
<= tsn-script-template
template= inline:
  #!/bin/sh
  exec ${tsn-rt-measures:location}/bin/slave -f {{ interface }} -a1 -p98 -d {{ gpio_direction_pin }} -u {{ gpio_pulse_pin }}

[publish-connection-information]
recipe = slapos.cookbook:publish
ip = {{ ip }}
ptp4l-launcher-{{ interface }} = $${ptp4l-launcher-{{ interface }}:rendered}
tsn-script = $${tsn-script:rendered}
