# A very simple console program. I could make it flashier but I can't be
# bothered.

&stdalias.inc

proc main
var line com

print [format "\n~BB*** AVIOS CONSOLE ***\n\n"]
while TRUE
	print ">"
	input line
	if line=""; continue; fi
	set com [head line]
	choose com
		value "ps"; call ps_proc; break
		value "kill"; call proc_action com [tail line]; break;
		value "halt"; call proc_action com [tail line]; break;
		value "restart"; call proc_action com [tail line]; break;
		value "run"; call run_proc [tail line]; break;
		value "exit"; exit 0

		default
		printnl "Unknown command"
	chosen
wend
endproc



proc ps_proc
var pid pname cnt info

print [format "\n~BB*** Processes at %s ***\n\n" [gettime time]]
foreach pid pname in $pcs
	set info [pcsinfo pid]
	printnl [format "~FY%-4d  ~FG%-10s  ~FT%s" pid pname [elements info 2 [count info]]]
nexteach
printnl [format "\nTotal of %d processes.\n" $pcs_count]
endproc



proc proc_action com pid
var pid2 pname status

if pid=""
	printnl com " which process?";  return
fi
foreach pid2 pname in $pcs
	if pid=pid2
		choose com
			value "kill"; trap [set status [kill pid]];  break;
			value "halt"; trap [set status [halt pid]];  break;
			value "restart"; trap [set status [restart pid]];  
		chosen
		if status=""
			printnl "Unable to " com " process.";  return
		fi
		printnl "Process " com "ed."
		return
	fi
nexteach
printnl "Process does not exist."
endproc	


proc run_proc line
var where device file pname pos pid res
var usage

set usage "run 'term/back/dev <device>' <filename> [<progname>] [<args>]"

if [set where [head line]]=""
	 printnl usage;  return
fi

if where="dev"
	set device [elements line 2];  set pos 3
else; set pos 2; fi

if [set file [elements line pos]]=""
	printnl usage;  return
fi
inc pos

if [set pname [elements line pos]]=""; set pname file; fi
inc pos

if pos<=[count line]
	set line [elements line pos [count line]]
else; set line ""; fi

if where="term"
	set res [trap [exec term orphan pid file pname line]]
else 
	if where="back"
		set res [trap [exec back orphan pid file pname line]]
	else; set res [trap [exec dev device orphan pid file pname line]]
	fi
fi

if res!=OK; printnl "Unable to run process"; fi
endproc