#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

check_files_exist() {

        for f in "$@"; do
	        if [ ! -e $f ]; then
	                echo "ERROR: $f does not exist" >&2
	                exit 1
	        else
	        echo "OK: $f is there"
	        fi
        done
}

check_data_exists() {

        result=$(/usr/bin/sqlite3 ~/.recon-ng/keys.db .dump | grep "'google_api','12345'"| wc -l)
        if [ $result -eq "0" ]; then
                echo "ERROR: data does not exist"
                exit 1
        else
                echo "OK: data is there"
        fi

}

run_help() {

        /usr/bin/recon-cli -h
	/usr/bin/recon-ng -h

}

test_recon-ng() {

    cat <<EOF > $AUTOPKGTEST_TMP/recon_ng_help
#!/usr/bin/expect
spawn /usr/bin/recon-ng
expect "\[recon-ng\]\[default\] >"
send "help\n"
expect "\[recon-ng\]\[default\] >"
send "show modules\n"
expect "\[recon-ng\]\[default\] >"
send "keys list\n"
expect "\[recon-ng\]\[default\] >"
send "keys add google_api 12345\n"
expect "\[recon-ng\]\[default\] >"
send "keys list\n"
expect "\[recon-ng\]\[default\] >"
send "workspaces list\n"
expect "\[recon-ng\]\[default\] >"
send "workspaces create test\n"
expect "\[recon-ng\]\[test\] >"
send "shell ls -l  ~/.recon-ng/workspaces/\n"
expect "\[recon-ng\]\[test\] >"
send "workspaces load default\n"
expect "\[recon-ng\]\[default\] >"
send "workspaces load test\n"
expect "\[recon-ng\]\[test\] >"
send "db query INSERT INTO domains (domain) VALUES ('kali.org')\n"
expect "\[recon-ng\]\[test\] >"
send "db query SELECT * FROM domains\n"
expect "\[recon-ng\]\[test\] > "
send "marketplace refresh\n"
expect "\[recon-ng\]\[test\] > "
send "marketplace install google_site_web\n"
expect "\[recon-ng\]\[test\] > "
send "modules load google_site_web\n"
expect "\[recon-ng\]\[test\]\[google_site_web\] >"
send "run\n"
expect "\[recon-ng\]\[test\]\[google_site_web\] >"
send "db query SELECT * FROM hosts\n"
expect "\[recon-ng\]\[test\]\[google_site_web\] >"
send "back\n"
expect "\[recon-ng\]\[test\] >"
send "marketplace search xss\n"
expect "\[recon-ng\]\[test\] >"
send "marketplace install xssed\n"
expect "\[recon-ng\]\[test\] >"
send "modules load xssed\n"
expect "\[recon-ng\]\[test\]\[xssed\] >"
send "info\n"
expect "\[recon-ng\]\[test\]\[xssed\] >"
send "run\n"
expect "\[recon-ng\]\[test\]\[xssed\] >"
send "back\n"
expect "\[recon-ng\]\[test\] >"
send "exit\n"
EOF

        chmod 755 $AUTOPKGTEST_TMP/recon_ng_help
        $AUTOPKGTEST_TMP/recon_ng_help
        check_files_exist ~/.recon-ng/workspaces/test/data.db
        check_data_exists
        rm -rf  ~/.recon-ng

}


###################################
# Main
###################################

for function in "$@"; do
        $function
done
