#!/bin/bash

hub_name="master"
host="192.168.100.8"
port="502"
qnum="16"
qoft="0"
scan_interval="1"

#==================================

config="modbus.yaml"
truncate --size 0 ${config}

cat >> ${config} << EOF
logo_modbus_${hub_name}:
  modbus:
    name: ${hub_name}
    type: tcp
    host: ${host}
    port: ${port}
    switches:
EOF

for num in $(seq 0 $qnum); do
    id=v$((num + qoft))
    cat >> ${config} << EOF
      - name: ${id}_on
        unique_id: ${id}_on
        write_type: coil
        address: $((num * 8 + 1))
      - name: ${id}_off
        unique_id: ${id}_off
        write_type: coil
        address: $((num * 8 + 2))
EOF
done

cat >> ${config} << EOF
    binary_sensors:
EOF

for num in $(seq 0 $qnum); do
    id=q$((num + qoft))s
    if [ "${num}" = "0" ]; then
        adr=$((num * 8 + 0))
    else
        adr=$((num + 8191))
    fi
    cat >> ${config} << EOF
      - name: ${id}
        unique_id: ${id}
        input_type: coil
        address: ${adr}
        scan_interval: ${scan_interval}
EOF
done

#==================================

config="switches.yaml"
truncate --size 0 ${config}

cat >> ${config} << EOF
logo_switches_${hub_name}:
  template:
    - switch:
EOF

for num in $(seq 0 $qnum); do
    id=q$((num + qoft))s
    cat >> ${config} << EOF
      - name: q$((num + qoft))
        unique_id: q$((num + qoft))
        default_entity_id: switch.q$((num + qoft))
        state: "{{ is_state('binary_sensor.${id}', 'on') }}"
EOF
    for action in on off; do
        cat >> ${config} << EOF
        turn_${action}:
          - action: switch.turn_on
            target:
              entity_id: switch.v$((num + qoft))_${action}
          - delay:
              milliseconds: 50
          - action: switch.turn_off
            target:
              entity_id: switch.v$((num + qoft))_${action}
          - action: python_script.set_state
            data:
              entity_id: binary_sensor.${id}
              state: '${action}'
EOF
  done
done
