#!/bin/bash
#
# Copyright (C) 2026 Nikos Mavrogiannopoulos
#
# This file is part of ocserv.
#
# ocserv is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# ocserv is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# This test validates occtl's client-side behavior against a stand-in for
# main's control socket (occtl-fake-server.py); it needs neither root nor
# a running server.

OCCTL="${OCCTL:-../src/occtl/occtl}"
srcdir=${srcdir:-.}
SOCKET=./occtl-local-$$.socket
LOG=occtl-local-$$.log
OUT=occtl-local-$$.out

if ! command -v python3 >/dev/null 2>&1;then
	echo "python3 is required for this test"
	exit 77
fi

function finish {
	stop_server
	rm -f ${SOCKET} ${LOG} ${OUT}
}
trap finish EXIT

# start_server SCENARIO: starts the fake server and waits for its socket
start_server() {
	rm -f ${SOCKET} ${LOG}
	python3 -I ${srcdir}/occtl-fake-server.py ${SOCKET} $1 ${LOG} &
	SPID=$!
	for i in $(seq 1 50);do
		test -S ${SOCKET} && return
		sleep 0.1
	done
	echo "FAIL: fake server did not create ${SOCKET}"
	exit 1
}

stop_server() {
	if test -n "${SPID}";then
		kill ${SPID} >/dev/null 2>&1
		wait ${SPID} 2>/dev/null
		SPID=""
	fi
}

# REQ-OCCTL-IPC-004: a server that never replies makes occtl fail after
# about 10 seconds, not hang.
echo " * occtl gives up on a server that does not reply..."
start_server silent
START=$(date +%s)
timeout 60 ${OCCTL} -n -s ${SOCKET} show status >${OUT} 2>&1
RET=$?
ELAPSED=$(( $(date +%s) - START ))
stop_server
if test ${RET} = 124;then
	echo "FAIL: expected occtl to time out after ~10s, got still waiting after 60s"
	exit 1
fi
if test ${RET} = 0;then
	echo "FAIL: expected a non-zero exit when the server does not reply, got 0"
	exit 1
fi
if test ${ELAPSED} -lt 8 || test ${ELAPSED} -gt 20;then
	echo "FAIL: expected occtl to give up after ~10s, got ${ELAPSED}s"
	exit 1
fi

# REQ-OCCTL-IPC-003: occtl refuses, without contacting the server, a user
# name too long for main's request buffer, and says so.
echo " * occtl rejects an over-long user name locally..."
LONGNAME=$(printf 'a%.0s' $(seq 1 300))
start_server silent
for cmd in "show user" "disconnect user" "terminate user";do
	rm -f ${LOG}
	timeout 30 ${OCCTL} -n -s ${SOCKET} ${cmd} ${LONGNAME} >${OUT} 2>&1
	RET=$?
	if test ${RET} != 1;then
		echo "FAIL: expected '${cmd} <300 chars>' to exit 1, got ${RET}"
		exit 1
	fi
	if test -s ${LOG};then
		echo "FAIL: expected '${cmd} <300 chars>' not to send a request, got: $(cat ${LOG})"
		exit 1
	fi
	if ! grep -q "too long" ${OUT};then
		echo "FAIL: expected '${cmd}' to report the user name as too long, got: $(cat ${OUT})"
		exit 1
	fi
done
stop_server

# REQ-OCCTL-SESSION-007: 'show session' matches the full session ID as
# well as the short one, and 'show sessions valid' prints its header even
# when the first session returned is not listed.
echo " * show session matches the full and the short session ID..."
start_server sessions
FULL=XyZ987AbCdEfGhIjKlMnOpQrStu
for sid in XyZ987 ${FULL};do
	${OCCTL} -n -s ${SOCKET} show session ${sid} >${OUT} 2>&1
	RET=$?
	if test ${RET} != 0;then
		echo "FAIL: expected 'show session ${sid}' to exit 0, got ${RET}"
		exit 1
	fi
	if ! grep -q "Username: alice" ${OUT};then
		echo "FAIL: expected 'show session ${sid}' to show user alice, got: $(cat ${OUT})"
		exit 1
	fi
	if grep -q "pending" ${OUT};then
		echo "FAIL: expected 'show session ${sid}' to show only the matching session, got: $(cat ${OUT})"
		exit 1
	fi
done

echo " * show session exits 2 when nothing matches..."
${OCCTL} -n -s ${SOCKET} show session zzzzzz >${OUT} 2>&1
RET=$?
if test ${RET} != 2 || ! grep -q "Session ID not found or expired" ${OUT};then
	echo "FAIL: expected 'show session zzzzzz' to report not found and exit 2, got ${RET}: $(cat ${OUT})"
	exit 1
fi

echo " * show sessions valid prints its header..."
${OCCTL} -n -s ${SOCKET} show sessions valid >${OUT} 2>&1
if ! head -n 1 ${OUT} | grep -q "session.*user.*status";then
	echo "FAIL: expected the column header on the first line, got: $(cat ${OUT})"
	exit 1
fi
if ! grep -q "^XyZ987 .*alice" ${OUT} || grep -q "pending" ${OUT};then
	echo "FAIL: expected only the authenticated session listed, got: $(cat ${OUT})"
	exit 1
fi
stop_server

# REQ-OCCTL-SESSION-008: 'show events' ignores an update with no user, and
# at the end of its input keeps listening for updates without spinning.
echo " * show events ignores an empty update and keeps listening at end of input..."
start_server events
TIMEFORMAT='%0U %0S'
{ time timeout 3 ${OCCTL} -n -s ${SOCKET} show events </dev/null >${OUT} 2>&1; } 2>${OUT}.time
RET=$?
stop_server
if test ${RET} != 124;then
	echo "FAIL: expected 'show events' to keep listening after the end of its input, got exit ${RET}: $(cat ${OUT})"
	exit 1
fi
read CPU_USER CPU_SYS <${OUT}.time
rm -f ${OUT}.time
if test $((CPU_USER + CPU_SYS)) -ge 1;then
	echo "FAIL: expected 'show events' to wait idle at the end of its input, got ${CPU_USER}s user and ${CPU_SYS}s system CPU time in 3s"
	exit 1
fi

# REQ-OCCTL-CLI-009: --json output is valid JSON, escapes every string,
# passes UTF-8 through and does not truncate long values.
echo " * --json show users is valid JSON..."
start_server users
${OCCTL} -n -s ${SOCKET} --json show users >${OUT} 2>/dev/null
stop_server
python3 -I - ${OUT} <<'PYEOF'
import json, sys
try:
    users = json.load(open(sys.argv[1], encoding="utf-8"))
except ValueError as e:
    print("FAIL: expected valid JSON from --json show users, got %s:" % e)
    print(open(sys.argv[1], encoding="utf-8", errors="replace").read())
    sys.exit(1)
u = users[0]
expected = {
    "Username": 'quote"back\\slash',
    "Groupname": "caf\u00e9-\u20ac",
    "DNS": ['dns"entry'],
    "User-Agent": "A" * 600,
}
for key, value in expected.items():
    if u.get(key) != value:
        print("FAIL: expected %s = %r, got %r" % (key, value, u.get(key)))
        sys.exit(1)
PYEOF
test $? = 0 || exit 1

# REQ-OCCTL-CLI-005: show status copes with a reply that lists no sec-mod
# PID.
echo " * show status without sec-mod PIDs..."
start_server status-nopids
${OCCTL} -n -s ${SOCKET} show status >${OUT} 2>&1
RET=$?
stop_server
if test ${RET} != 0;then
	echo "FAIL: expected show status to exit 0, got ${RET}: $(cat ${OUT})"
	exit 1
fi
if ! grep -q "Server PID: 4242" ${OUT} || grep -q "Sec-mod PID" ${OUT};then
	echo "FAIL: expected the server PID and no sec-mod PID, got: $(cat ${OUT})"
	exit 1
fi

# REQ-OCCTL-CLI-001: the documented option forms are accepted; anything
# else prints usage and exits 1.
echo " * documented options are accepted..."
start_server status-nopids
for opts in "-s ${SOCKET}" "--socket-file ${SOCKET}" "--socket-file=${SOCKET}" \
	    "-j -s ${SOCKET}" "--json -s ${SOCKET}" "-n -s ${SOCKET}" \
	    "--no-pager -s ${SOCKET}" "--debug -s ${SOCKET}";do
	${OCCTL} ${opts} show status >${OUT} 2>&1
	RET=$?
	if test ${RET} != 0 || grep -q "OPTIONS" ${OUT};then
		echo "FAIL: expected 'occtl ${opts} show status' to succeed, got ${RET}: $(cat ${OUT})"
		exit 1
	fi
done
stop_server
for opt in -h --help -v --version;do
	${OCCTL} ${opt} >${OUT} 2>&1
	if test $? != 0;then
		echo "FAIL: expected 'occtl ${opt}' to exit 0, got $?"
		exit 1
	fi
done

echo " * undocumented options are rejected..."
for opt in -x --j -json --jxyz -d --no-pagerx;do
	${OCCTL} ${opt} show status >${OUT} 2>&1
	RET=$?
	if test ${RET} != 1 || ! grep -q "OPTIONS" ${OUT};then
		echo "FAIL: expected 'occtl ${opt} show status' to print usage and exit 1, got ${RET}: $(cat ${OUT})"
		exit 1
	fi
done
${OCCTL} -s >${OUT} 2>&1
RET=$?
if test ${RET} != 1 || ! grep -q "OPTIONS" ${OUT};then
	echo "FAIL: expected 'occtl -s' without a file to print usage and exit 1, got ${RET}: $(cat ${OUT})"
	exit 1
fi

# REQ-OCCTL-ERR-004: 'show events' recognises that the server closed the
# connection, says so, and exits 0.
echo " * show events reports a closed connection..."
start_server events-close
START=$(date +%s)
timeout 30 ${OCCTL} -n -s ${SOCKET} show events >${OUT} 2>&1 < <(sleep 10)
RET=$?
ELAPSED=$(( $(date +%s) - START ))
stop_server
if test ${RET} != 0 || ! grep -q "server closed the connection" ${OUT};then
	echo "FAIL: expected 'show events' to report the closed connection and exit 0, got ${RET}: $(cat ${OUT})"
	exit 1
fi
if ! grep -q "one listener at a time" ${OUT};then
	echo "FAIL: expected the closed-connection message to mention the single listener, got: $(cat ${OUT})"
	exit 1
fi
if test ${ELAPSED} -ge 10;then
	echo "FAIL: expected 'show events' to stop when the connection closed, got it running until its input ended (${ELAPSED}s)"
	exit 1
fi

exit 0
