#!/bin/bash
# Copyright Atomicorp 2021
# All rights reserved
VERSION=0.3

# Notes
#                   list endpoints
#                   tell a remote to connect to $SERVER for tcp scanning
#                   tell a remote to configure itself as a clamd server


function show_help() {
        echo
	echo "Atomicorp Malware Scan CLI"
	echo "Version: ${VERSION}"
        echo "Usage: $0 -a|-g group|-i id -s <path>|-u|-x"
	echo
        echo "  example: $0 -a -s /etc"


	echo
	echo 
	echo "Command line paramenters"
	echo
	echo "  Target requires one of the following"
	echo "    -a 			All agents"
	echo "    -g <group> 		All agents in group <group>"
	echo "    -l 			List Agents"
	echo "    -i <id>		Specified Agent ID"
	echo 
	echo "  Action requires one of the following"
	echo "    -s <path>		malware scan <path>"
	echo "    -u 			update signatures"
	echo "    -x <type>		initialize scanner (local or remote)"
	echo
	exit 1


}

function scan_host() {
	id=$1
	SCANID=$(date +%s)
	# TODO: is the ID valid
	/var/ossec/bin/agent_control -f malware-scan0 -u $id -b "${SCAN} scanid:${SCANID}" 

}


function check_scan() {
	# Input validation
	if [[ ! $SCAN ]] ; then
		echo
		echo "  Error: No scan paths declared"
		echo
		exit 1
	fi
}

if [ ! $1 ]; then
	show_help
fi


while getopts ":lahug:i:s:x:" option; do
   case $option in
	# Scan every node
	a) 
		ALL=1
		;;

	# Scan all in a group
	g)
		GROUP=$OPTARG
		;;
	# Scan a specific node
      	i) 
		ID=$OPTARG
		;;
	# List agents
      	l) 
		LIST=1
		;;
	# Scan path parameters
      	s) 
		SCAN=$OPTARG
		;;
	# Update a target
	u)
		UPDATE=1
		;;
	# Initialize
	x)
		INIT=$OPTARG
		;;
    \?) # display Help
      		show_help
      		exit 1;;
   esac
done


# Main
if [[ -z $ALL && -z $GROUP && -z $ID && -z $INIT && -z $UPDATE && -z $LIST ]]; then
	show_help
fi

# Build our list
if [[ $ALL ]]; then
	# Get list of all online agents
	for list in $(/var/ossec/bin/agent_control -lc -s |grep Active |awk -F, '{print $1}');  do
		targets="$targets $list"
		
	done
elif [[ $GROUP ]]; then
	for list in $(/var/ossec/bin/agent_groups -g $GROUP -l | awk '/ID/ {print $2}') ; do	
		targets="$targets $list"
	done
elif [[ $LIST ]]; then
	echo
	echo "Connected Agents:"
	/var/ossec/bin/agent_control -lc |egrep -v 000 |grep ID
	echo
	exit
elif [[ $ID ]]; then
	targets=$ID
else
	echo 
	echo "  Error: No targets declared"
	echo
	exit 1
	
fi


if [[ $SCAN ]] ; then
	for agent in $targets; do
		echo "Scanning host: $agent path ${SCAN}"
		scan_host $agent
	done
elif [[ $UPDATE ]]; then
	for agent in $targets; do
		echo "Updating host: $agent"
		SCAN="update"
		scan_host $agent 
	done

elif [[ $INIT ]]; then
	for agent in $targets; do
		echo "Initalizing host: $agent as type $INIT"
		if [[ $INIT == "local" ]]; then
			SCAN="init-local"
		elif [[ $INIT == "remote" ]]; then
			SCAN="init-remote"
		else
			echo "  Error: Invalid init type"
			exit 1
		fi
		scan_host $agent
	done
else
	echo "  Error: no valid commands passed"
	show_help
fi
