You’re on the right way but probably thinking too complicated.
You just need the minimum GROUP_COUNT()-value of Your trunks or in other words: A ranking by GROUP_COUNT(). The trunk with the lowest GROUP_COUNT will be used (except the GROUP_COUNT exceeds the amount of channels available for the trunk, but that’s an addition).
Thus the question is: How to order 4 values ascending? You may do this within any AGI script or You may try to do it in dialplan logic based on any sort algorithm You may find.
Here is an (AEL) example where Test represents Your 4 lines (in the form LineNumber-GROUP_COUNT()&)
After Looping through the sort-algorythm (optimized bubble-sort) the NoOp gives You the mostleft element in the string which will be the Line with the lowest GROUP_COUNT (ascending order)
Set(Test=1-1&2-1&3-0&4-1);
Set(n=4);
while( ${n} > 1 ) {
Set(newn=1);
for (i=1; ${i}<${n}-1; i=$[${i}+1]) {
Set(tmp=${CUT(Test,&,${i})});
Set(tmp1=${CUT(Test,&,$[${i}+1])});
if (${CUT(tmp,-,2)} > ${CUT(tmp1,-,2)}) {
Set(Test1=);
for (j=1; ${j}<${i}; j=$[${j}+1]) {
Set(PUSH(Test1,&)=${CUT(Test,&,${j})});
}
Set(PUSH(Test1,&)=${tmp1});
Set(PUSH(Test1,&)=${tmp});
for (j=$[${i}+2]; ${j}<=4; j=$[${j}+1]) {
Set(PUSH(Test1,&)=${CUT(Test,&,${j})});
}
Set(Test=${Test1});
Set(newn=$[${i}+1]);
}
}
Set(n=${newn});
}
NoOp(${SHIFT(Test,&)});
And - for those who don’t want to implement the sorting itself - Asterisk even has a built-in Sorting function:
Set(Test=1:1,2:1,3:0,4:1);
Set(Test=${SORT(${Test})});
NoOp(${SHIFT(Test)});
The idea is quite the same, the format differs (and needs to be in this way for the SORT-function) and in the example the NoOp just shows the ID of our line which should be used (As after the sort the GROUP_COUNT() is eleminated from the Test-variable in this implementation)