#!/bin/bash

###############################################################################
# Cowrie launcher
###############################################################################

set -e

COWRIE_HOME="/var/lib/cowrie"
COWRIE_VENV="${COWRIE_HOME}/venv"

export COWRIE_HOME
export PYTHONPATH="${COWRIE_HOME}/app/src${PYTHONPATH:+:${PYTHONPATH}}"

cd "${COWRIE_HOME}"

#
# Cowrie must never run as root.
#

if [ "$(id -u)" -eq 0 ]; then

    echo
    echo "ERROR: You must not run cowrie as root!"
    echo
    echo "Run it as the cowrie user:"
    echo
    echo "  sudo -u cowrie cowrie foreground"
    echo

    exit 1

fi

case "${1:-}" in

    start)
        exec "${COWRIE_VENV}/bin/twistd" \
            --pidfile "${COWRIE_HOME}/run/cowrie.pid" \
            cowrie
        ;;

    stop)
        if [ -f "${COWRIE_HOME}/run/cowrie.pid" ]; then
            PID="$(cat "${COWRIE_HOME}/run/cowrie.pid")"
            if kill -0 "${PID}" 2>/dev/null; then
                kill "${PID}" 2>/dev/null || true
            fi
        else
            echo "Cowrie is not running."
        fi
        ;;

    restart)
        "$0" stop
        sleep 1
        exec "$0" start
        ;;

    status)
        if [ -f "${COWRIE_HOME}/run/cowrie.pid" ]; then
            PID="$(cat "${COWRIE_HOME}/run/cowrie.pid")"
            if kill -0 "${PID}" 2>/dev/null; then
                echo "Cowrie is running."
                echo "PID: ${PID}"
                exit 0
            fi
        fi
        echo "Cowrie is not running."
        exit 1
        ;;

    foreground)
        exec "${COWRIE_VENV}/bin/twistd" \
            --nodaemon \
            cowrie
        ;;

    *)
        echo
        echo "Cowrie Honeypot"
        echo
        echo "Usage:"
        echo "  cowrie start"
        echo "  cowrie stop"
        echo "  cowrie restart"
        echo "  cowrie status"
        echo "  cowrie foreground"
        echo
        exit 1
        ;;
esac
