Something similar to this. Haven't time to check it but that should work:
;magazinesTest.sqs
;Execute this script with
;unitName exec "magazinesTest.sqs"
_unit = _this
;All magazines that take up a single slot
_singleSlotArray = ["20Rnd_556x45_Stanag","30Rnd_556x45_Stanag","30Rnd_556x45_StanagSD","30Rnd_556x45_G36","30Rnd_9x19_MP5SD","30Rnd_9x19_MP5","5Rnd_762x51_M24","10Rnd_127x99_m107","30Rnd_545x39_AK","30Rnd_545x39_AKSD","10Rnd_762x54_SVD","5Rnd_127x108_KSVK","SmokeShell","SmokeShellRed","SmokeShellGreen","HandGrenade","HandGrenadeTimed","FlareWhite_M203","FlareGreen_M203","FlareRed_M203","FlareYellow_M203","1Rnd_HE_M203","FlareWhite_GP25","FlareGreen_GP25","FlareRed_GP25","FlareYellow_GP25","1Rnd_HE_GP25"]
;All magazines that take up double slots
_doubleSlotArray = ["200Rnd_556x45_M249","20Rnd_556x45_Stanag","30Rnd_556x45_Stanag","30Rnd_556x45_StanagSD","100Rnd_762x51_M240","M136","JAVELIN","STINGER","100Rnd_762x54_PK","PG7V","PG7VR","STRELA","PipeBomb","TimeBomb","Mine","MineE"]
;Count the number of magazines
_numMags = count magazines _unit
;Magazine array
_magArray = magazines _unit
;If the unit has a pistol, check for pistol mags. Otherwise, they can't have pistol mags.
if ((_unit hasWeapon "M9") || (_unit hasWeapon "M9SD") || (_unit hasWeapon "Makarov") || (_unit hasWeapon "MakarovSD")) then {_magazineCounter = 14} else {_magazineCounter = 10}
_i = 0
#magsLoop
if ((_i - 1) > _numMags) then {goto "ExecuteAction"}
_thisMag = _magArray select _i
if (_thisMag in _singleSlotArray) then {_magazineCounter = _magazineCounter - 1}
if (_thisMag in _doubleSlotArray) then {_magazineCounter = _magazineCounter - 2}
_i = _i + 1
goto "magsLoop"
#ExecuteAction
;Your code to do whatever goes here
if (_magazineCounter > 1) then {_unit addMagazine "Pipebomb"}
exit