/*rx */
/* valid states
 ''   - none set
 DOWN - AmiTCP not running
 LOCALHOST - AmiTCP running, but $GATEWAY=localhost
 ONLINE    - up ruuning and connected
 OFFLINE   - up ruuning and not connected
 DROPPED   - last time we checked we were online, now we're offline and no-one set the state to DROPPING
 DROPPING  - a warning state, we are gonna drop the connection soon so don't bother running anythign else
*/
    
parse arg state

if state ~= '' & state ~= 'DROPPING' then
do
    say 'Usage: connectstate [DROPPING]'
    exit 1
end

if ~ show('P','AMITCP') then
do
    SetVar('CONNECTSTATE','DOWN','GLOBAL')
    exit 20
end   

envar=GetVar('GATEWAY')
if upper(envar) = 'LOCALHOST' then
do
    SetVar('CONNECTSTATE','LOCALHOST','GLOBAL')
    exit 5
end

envar=GetVar('CONNECTSTATE')
if envar ~= '' then
do
    setstate=envar
    if upper(setstate) = 'LOCALHOST' then
    do
        exit 5
    end
end

options results
address AMITCP 'QUERY ROUTES ALL'
if word(result,4) = 'UG' then
do
    curstate = 'ONLINE'
    address command 'netecho $GATEWAY > NIL:'
    if RC = 20 then curstate = 'DROPPED'
end
else do
    curstate = 'OFFLINE'
end

if curstate = 'ONLINE' then
do
    if setstate = 'DROPPING' | state = 'DROPPING' then
    do
        SetVar('CONNECTSTATE','DROPPING','GLOBAL')
    end
    else do
        SetVar('CONNECTSTATE','ONLINE','GLOBAL')
    end
    exit 0
end
else if curstate = 'OFFLINE' | curstate = 'DROPPED' then
do
    if setstate = 'ONLINE' then
    do
        SetVar('CONNECTSTATE','DROPPED','GLOBAL')
    end
    else do
        SetVar('CONNECTSTATE','OFFLINE','GLOBAL')
    end
    exit 5
end
exit 99

