#!/bin/bash -x

# Thread network setup
## Create a clean slate
ot-ctl thread stop
ot-ctl ifconfig down
ot-ctl factoryreset
rm /var/lib/thread/*
rm /var/chip-tool/*

sleep 5

## Setup a new thread network
ot-ctl dataset init new
ot-ctl dataset channel 11
ot-ctl dataset panid 0x976e
ot-ctl dataset extpanid f581065e27eb4a59
ot-ctl dataset networkname TestNet
ot-ctl dataset networkkey d645efebea99fd80fc10addc20bcdd93
ot-ctl dataset pskc f254a33b452bf277b1329750f2922e3a
ot-ctl dataset commit active
ot-ctl prefix add fd08:b89:78:f372::/64 paos med
ot-ctl ifconfig up
ot-ctl thread start
ot-ctl dataset active -x

# Commissioning
## Save the active datset to be used in commissioning
DATASET=$(ot-ctl dataset active -x | head -n1 | tr -d '\r')

## Commission the light bulb
chip-tool pairing code-thread 2 hex:$DATASET MT:6FCJ142C00KA0648G00 --bypass-attestation-verifier true

sleep 5

# Configure 3 groups
chip-tool groupsettings add-keysets 0xaaaa 0 0x21dfe0 hex:281b29592d521ea8a8d57a4a7639511b
chip-tool groupkeymanagement key-set-write '{"groupKeySetID":42,"groupKeySecurityPolicy":0,"epochKey0":"281b29592d521ea8a8d57a4a7639511b","epochStartTime0":2220000,"epochKey1":"c7cb12d00355e03c942a0b7447d05c1b","epochStartTime1":2220001,"epochKey2":"ba5aaef06db2a60920fd54166e734018","epochStartTime2":2220002}' 2 0

chip-tool groupsettings add-group grp3 3
chip-tool groupsettings bind-keyset 3 43690

chip-tool groupsettings add-group grp4 4
chip-tool groupsettings bind-keyset 4 43690

chip-tool groupsettings add-group grp5 5
chip-tool groupsettings bind-keyset 5 43690

chip-tool groupkeymanagement write group-key-map '[{"groupId":3,"groupKeySetID":42},{"groupId":4,"groupKeySetID":42},{"groupId":5,"groupKeySetID":42}]' 2 0
chip-tool accesscontrol write acl '[{"fabricIndex":1,"privilege":5,"authMode":2,"subjects":[112233],"targets":null},{"fabricIndex":1,"privilege":3,"authMode":3,"subjects":[3,4,5],"targets":[{"cluster":null,"endpoint":1,"deviceType":null},{"cluster":null,"endpoint":1,"deviceType":null},{"cluster":null,"endpoint":1,"deviceType":null}]}]' 2 0

chip-tool groups add-group 3 grp3 2 1 # Success
chip-tool groups add-group 4 grp4 2 1 # Success
chip-tool groups add-group 5 grp5 2 1 # Fail: "Unable to listen to group" on edge device, even though it appears successful from chip-tool's perspective

# Control the light bulb using each group
## First group works
chip-tool onoff on 0xFFFFFFFFFFFF0003 0
sleep 2
chip-tool onoff off 0xFFFFFFFFFFFF0003 0
sleep 2

## Second group works
chip-tool onoff on 0xFFFFFFFFFFFF0004 0
sleep 2
chip-tool onoff off 0xFFFFFFFFFFFF0004 0
sleep 2

## Third group fails, no traffic comes through on the light bulb
chip-tool onoff on 0xFFFFFFFFFFFF0005 0
sleep 2
chip-tool onoff off 0xFFFFFFFFFFFF0005 0

