#!/usr/bin/env bash

# Check if the script is running as user _gvm
if [ "$(whoami)" != "_gvm" ]; then
  echo "This script must be run as user _gvm."
  exit 1
fi

# Check if the number of arguments is correct
if [ $# -lt 2 ]; then
  echo "Usage: $0 <password> <target_host>"
  exit 1
fi

# Extract arguments
password="$1"
target_host="$2"

# Generate target name by replacing '/' with '_' in case of network address
target_name=$(echo -n "$target_host" | sed 's/\//_/g')

# Create target
echo "[+] Creating target"
target_id=$(gvm-cli --gmp-username admin --gmp-password "$password" socket --xml "<create_target><name>$target_name</name><hosts>$target_host</hosts><port_range>1-65535</port_range></create_target>" | grep -o 'id="[^"]*"' | sed -e 's/id="//' -e 's/"//')
if [ -z "$target_id" ]; then
  echo "[-] Failed to create target"
  exit 1
fi

# Create task
echo "[+] Creating task"
task_id=$(gvm-cli --gmp-username admin --gmp-password "$password" socket --xml "<create_task><name>Task_$target_name</name><comment>Scanning $target_host</comment><config id='daba56c8-73ec-11df-a475-002264764cea'/><target id='$target_id'/></create_task>" | grep -o 'id="[^"]*"' | sed -e 's/id="//' -e 's/"//')
if [ -z "$task_id" ]; then
  echo "[-] Failed to create task"
  exit 1
fi

# Start task
echo "[+] Starting task"
report_id=$(gvm-cli --gmp-username admin --gmp-password "$password" socket --xml "<start_task task_id='$task_id'/>" | grep -oP '(?<=<report_id>).*?(?=</report_id>)')

# Wait for task to complete
echo "[-] Waiting for scan result. This may take a while."
while true; do
    output=$(gvm-cli --gmp-username admin --gmp-password "$password" socket --xml "<get_tasks task_id='$task_id'/>" 2>/dev/null | xmllint --format -)
    if echo "$output" | grep -q '<status>Done</status>'; then
        break
    fi
    sleep 60
done
echo "[+] The scan is complete."

# Create report
echo "[+] Printing scan results..."
gvm-cli --gmp-username admin --gmp-password "$password" socket --xml "<get_results task_id=\"$task_id\" filter='notes=1 overrides=1'/>" |\
xmlstarlet sel -t -m "//result" \
  -v "host" -o "|" \
  -v "host/hostname" -o "|" \
  -v "port" -o "|" \
  -v "threat" -o "|" \
  -v "name" -o "|" \
  -v "severity" -n |
sort -t'|' -k6,6nr |
awk -F'|' '{printf "%s\t%s\t%s\t%s\t%s\n", $1, $2, $3, $4, $5}'