#!/usr/bin/env bash
set -euo pipefail

ZAP="http://127.0.0.1:8080"
TARGET="https://staging.example.com"
CONTEXT_NAME="invoice-auth"
LOGIN_URL="https://staging.example.com/login"
USERNAME="zap_test_user"
PASSWORD="REPLACE_ME"

# Start ZAP separately, for example:
# ./zap.sh -daemon -host 0.0.0.0 -port 8080 #   -config api.disablekey=true #   -config api.addrs.addr.name=.* #   -config api.addrs.addr.regex=true

curl -s "$ZAP/JSON/context/action/newContext/?contextName=${CONTEXT_NAME}"
curl -s "$ZAP/JSON/context/action/includeInContext/?contextName=${CONTEXT_NAME}&regex=https://staging\.example\.com.*"

curl -s "$ZAP/JSON/authentication/action/setAuthenticationMethod/?contextId=1&authMethodName=formBasedAuthentication&authMethodConfigParams=loginUrl=${LOGIN_URL}%26loginRequestData=username%3D%7B%25username%25%7D%26password%3D%7B%25password%25%7D"
curl -s "$ZAP/JSON/sessionManagement/action/setSessionManagementMethod/?contextId=1&methodName=cookieBasedSessionManagement"

curl -s "$ZAP/JSON/users/action/newUser/?contextId=1&name=${USERNAME}"
curl -s "$ZAP/JSON/users/action/setAuthenticationCredentials/?contextId=1&userId=0&authCredentialsConfigParams=username=${USERNAME}%26password=${PASSWORD}"
curl -s "$ZAP/JSON/users/action/setUserEnabled/?contextId=1&userId=0&enabled=true"

curl -s "$ZAP/JSON/spider/action/scanAsUser/?contextId=1&userId=0&url=${TARGET}&recurse=true"
curl -s "$ZAP/JSON/ascan/action/scanAsUser/?url=${TARGET}&contextId=1&userId=0&recurse=true"
curl -s "$ZAP/OTHER/core/other/htmlreport/" > zap-report.html
