I’m working on something similar, but haven’t finished yet. It’s rough but does pretty much what yours does, feel free to incorporate some/all/none of this:
[macro-dialout-trunk-predial-hook]
exten => s,1,Noop(Entering user defined context macro-dialout-trunk-predial-hook in extensions_custom.conf)
; notification for all emergency calls
exten => s,n,GoSubIf($["${EMERGENCYROUTE}"="YES"]?dynamic-emerg-cid,s,1)
exten => s,n(finished),MacroExit
[dynamic-emerg-cid]
exten => s,1,NoOp(Entering user defined context dynamic-emerg-cid in extensions_custom.conf)
exten => s,n,GotoIF($["${CHANNEL(channeltype)}" = "PJSIP"]?pjsip)
exten => s,n,GotoIF($["${CHANNEL(channeltype)}" = "SIP"]?sip)
exten => s,n,Noop(Unable to get channel type, exiting)
exten => s,n,Goto(exit)
; get ip for pjsip contact
exten => s,n(pjsip),Set(endpoint_addr=${CHANNEL(pjsip,remote_addr)})
exten => s,n,Set(ip_addr=${CUT(endpoint_addr,:,1)})
exten => s,n,Goto(cid)
; get ip for sip peer
exten => s,n(sip),Set(ip_addr=${CHANNEL(peerip)})
exten => s,n,Goto(cid)
; set outbound CID based on regex's
exten => s,n(cid),ExecIf(${REGEX("(192\.168\.7\.[0-9]{1,3})" ${ip_addr})}?Set(CALLERID(number)=5551117777))
exten => s,n,ExecIf(${REGEX("(10\.224\.50\.[0-9]{1,3})" ${ip_addr})}?Set(CALLERID(number)=5551118888))
exten => s,n(exit),return()