#!/bin/bash

locate_info()
{
cat << EOF
$0 has not found, via locate, the path of the 'generic/' location

you have three options to solve this issue:
  . install locate, launch updatedb and restart sniffjoke-autotest
  . you already has locate, but you need to updatedb
  . or, use the option:
         -d /directory/of/sniffjoke/locations/
    checking that in 'locations/' will be present 'generic/'

note: $0 use as marker the file THIS_IS_GENERIC
EOF
}

shopt -s expand_aliases
alias echo="echo -e"

red="\e[1;31m"
green="\e[1;32m"
yellow="\e[1;33m"
blue="\e[1;34m"
violet="\e[1;35m"
white="\e[1;39m"

#default values
VERSION="041"
LOCATION=
LOCSDIR=
GENERICDIR=
USERNAME=
GROUPNAME=
SERVERURL=
GNUPGTRUST="NO"
REPN=1
firstsimple=

usage()
{
cat << EOF
usage: $0 options

  This script runs plugins test along different destinations OS to determinate the 
selection of plugins and options that correctly works in the current location. 

  Every workplace (office, home, freewifi) you use, neet to be setup as location.

  Having a location correctly configurated IS THE ONLY WAY to have SniffJoke working;
  technical details will be found in: 
http://www.delirandom.net/sniffjoke/sniffjoke-locations

OPTIONS:
   -h      show this message
   -l      location name                                       (required)
   -n      number of replicas to be passed for the single hack (default 1)
   -g      specify the group to privilege downgrade            (default: nogroup)
   -u      specify the user to privilege downgrade             (default: nobody)
EOF
}

dump_plugin_file() {
cat >> $PLUGINLIST <<__EOF__
fake_close_fin,PRESCRIPTION
fake_close_fin,MALFORMED
fake_close_fin,GUILTY
fake_close_rst,PRESCRIPTION
fake_close_rst,MALFORMED
fake_close_rst,GUILTY
fake_data,PRESCRIPTION
fake_data,MALFORMED
fake_data,GUILTY
fake_seq,PRESCRIPTION
fake_seq,MALFORMED
fake_seq,GUILTY
fake_syn,PRESCRIPTION
fake_syn,MALFORMED
fake_syn,GUILTY
fake_window,PRESCRIPTION
fake_window,MALFORMED
fake_window,GUILTY
fragmentation,INNOCENT
shift_ack,PRESCRIPTION
shift_ack,MALFORMED
shift_ack,GUILTY
valid_rst_fake_seq,INNOCENT
__EOF__
}

trusted_server_contact()
{
    # this is the trustable key
    #
    # pub   1024D/7D9E677D 2011-05-21
    #       Key fingerprint = F37C 2042 5052 27E2 2FD7  D511 947F 574B 7D9E 677D
    # uid                  SniffJoke project (http://www.delirandom.net/sniffjoke)
    #
    # and, to be sure became installed in every box:
    #
    # $ gpg -a --export 7D9E677D
    # -----BEGIN PGP PUBLIC KEY BLOCK-----
    # Version: GnuPG v1.4.10 (GNU/Linux)
    # 
    # mQGiBE3YHaMRBACLou45ad2TnK6iQKHym7Q4AuySv+pxFVjd5QEJ/Gy3b5dM4bRn
    # y1NzuTxnCPpuR4c/Iv+rZbhSsoxqTAZ8YYJ4wdFEvDTLap9l1n8D66oYzYr9C1Tl
    # lxeCtz4hzJZK1M8agoBpnu0xRWCkZNziSdKPQGAlrSaTzLcrKaNYx727uwCg8XKF
    # fMe93oJtEmKSxl6S1V+mbOsD/j/2CfDuhtjJnHZWgmrlBrtghw9BubCi/o+TWNPs
    # a++FqUI+tw5G2CZiOS2HzR6/UIEcWr99HBGnyC6+B3TzyiU20T22DOCt8Dii65qt
    # j47rhKFAo6kUlJymY0X+fLzxxNBzS7BzrNIvLzCcdNmDsxjGtGtCedJCV09WNgRk
    # SgVpA/sHMF1rsYb4LGeg+unp7b6IyJgpeGagvTVqS366IReoftPatvbP18t4pdlD
    # wkGG2MnVtQFgz8o5LiS1AR6B74Lpr0FTIhMBUpi7A1JOetsliNImNPkrMJs1sYog
    # tWv59uDOYj7TfV2F9jMu1hWoedCLMsvwouXwaqFtk13PFg2hMbQ3U25pZmZKb2tl
    # IHByb2plY3QgKGh0dHA6Ly93d3cuZGVsaXJhbmRvbS5uZXQvc25pZmZqb2tlKYhg
    # BBMRAgAgBQJN2B2jAhsDBgsJCAcDAgQVAggDBBYCAwECHgECF4AACgkQlH9XS32e
    # Z31bjgCeIm4ft9zSztcsVFjdWnOyyKvNWckAnA6Ndf9Ps97Ve0u82ySNYFgHVqRR
    # iEoEEBECAAoFAk3YHmsDBQJ4AAoJELhCCT3GdlQwEl4AnA/OX42uxbC5GCn2tgBC
    # mJ7sBRawAKDfZ2G6q0S+JUWlQDFtbHwocCaIYA==
    # =FK0c
    # -----END PGP PUBLIC KEY BLOCK-----
    #
    # is a "sign only" key, that's why is so short

    GPGBIN=`which gpg`
    if [ ! -z "$GPGBIN" ]; then

        # REMIND: this is needed to avoid:
        KEYRINGOPT="--no-permission-warning --no-default-keyring --keyring $TEMPDIR/$LOCATION/sj.gpgkeyring"
        # gpg: WARNING: unsafe ownership on configuration file `/home/vecna/.gnupg/gpg.conf'
        # gpg: error reading key: public key not found

        echo "${green}GNuPG binary found: checking if key (1024D/7D9E677D 2011-05-21) is present on your keyring..."
        echo "${blue}"
        $GPGBIN --list-keys 7D9E677D >/dev/null 2>&1
        if [ "$?" != "0" ]; then
            echo "${yellow} SniffJoke key not found: importing in a temporary keyring..."
            tput sgr0
            $GPGBIN $KEYRINGOPT --keyserver pgp.mit.edu --recv-key 7D9E677D 
        fi

        fingercheck=`$GPGBIN $KEYRINGOPT --fingerprint 7D9E677D | grep "fingerprint" | tr -d " " | cut -b 16- 2>&1`
        if [ -z "$fingercheck" ]; then
            echo "${red} Unable to retriver SniffJoke's key from ${blue}pgp.mit.edu${red}: Not required, but understimable neither"
        else
            if [ "$fingercheck" = "F37C2042505227E22FD7D511947F574B7D9E677D" ]; then
                echo "${green} Key verified: 7D9E677D, SniffJoke project (http://www.delirandom.net/sniffjoke)"
                GNUPGTRUST="YEP"
            else
                echo "${red} Something is wrong with your keys, keyserver or gpg: unable to verify the key"
                # default, GNUPGTRUST="NO"
            fi
        fi
    else
        echo "${red}gnupg not found! not required, but for paranoic guys, that's things matters"
    fi
}

routing_table_log() {
    route -n > $WORKDIR/route-$1.log
}

group_check() 
{
    GROUPNAME=`groups $USERNAME | cut -d " " -f 3` 
    if [ -z "$GROUPNAME" ]; then
        echo "${red}Unable to found, in your system, the group of $USERNAME. ${white}please specify with the option -g and -u username/group"
        echo "(hey, you package mantainer! is better you create a dedicated sniffjoke user/group)"
        echo "A group is required because sniffjoke drop privileges. You will need to customize the ${green}sniffjoke-server.conf ${white}"
        echo "because by default is used nobody/nogroup"
        tput sgr0; exit
    fi
}

start_test() {
    REPLICAn=$1
    if [[ $PLUGIN =~ ([a-z_]+),([A-Z0-9\+]+) ]]; then
        PNAME=${BASH_REMATCH[1]}
        SCRAMBLE=${BASH_REMATCH[2]}
        TESTID=$PNAME/$SCRAMBLE
    fi
    mkdir -p $TESTID
    echo "${green}.----"
    echo "${green}| ${blue}Plugin Name\t${yellow}\t[$PNAME]"
    echo "${green}| ${blue}Scramble\t${yellow}\t[$SCRAMBLE]"
    echo "${green}| ${blue}TestID\t${yellow}\t[$TESTID]"
    echo "${green}| ${blue}Test directory${yellow}\t[$TEMPDIR/$LOCATION/$TESTID]${white}"
    # $SERVER is like http://www.delirandom.net/sjA/pe.php
    for i in `seq 1 $REPLICAn`;
    do
        WORKDIR=$TESTID/replica-${i}
        mkdir -p $TESTID/replica-${i}

        cp $LOCSDIR/generic/sniffjoke-service.conf $TESTID/replica-${i}/
        echo $SERVER_IP > $WORKDIR/ipwhitelist.conf

        if [ -e $firstsimple/ttlfocusmap.bin ]; then
            cp $firstsimple/ttlfocusmap.bin $TESTID/replica-${i}/
            cp $TEMPDIR/$LOCATION/iptcp-options.conf $TESTID/replica-${i}
            echo "${green}| * COMBINATION OF TESTS (${yellow}$PLUGNDX/$PLUGIN_NUMBER${green}) REPLICA (${yellow}$i/$REPLICAn${green})"
        else
            echo "${green}| * ${blue}Goal:\t${green}\t[generate ttlfocusmap.bin, and test sniffjoke without any esoteric network trick]${white}"
            cp $LOCSDIR/generic/iptcp-options.conf $TESTID/replica-${i}
        fi

        echo "${yellow}** Executing sniffjoke with $PLUGIN combo${white}"
        echo "sniffjoke --debug 6 $UGPD --start --dir $TEMPDIR/$LOCATION/$TESTID --location replica-${i} --only-plugin $PLUGIN --no-udp --whitelist"

        $SNIFFJOKEBIN --debug 6 $UGPD --start --dir $TEMPDIR/$LOCATION/$TESTID --location replica-${i} --only-plugin $PLUGIN --no-udp --whitelist >/dev/null 2>&1
        sleep 0.8
        routing_table_log "after"

        $SNIFFJOKECLIBIN stat > $WORKDIR/dumpService_stat.log
        if [ "$?" -eq 0 ]; then
            echo "${green}sniffjoke is correctly running${white}"
        else
            echo "${red}sniffjoke is not running - fatal error - remove $TEMPDIR/$LOCATION by hand${white}"
            tput sgr0; exit
        fi

        INTERFACE=`cat $WORKDIR/dumpService_stat.log | grep "hijacked interface:" | awk '{print $3}'`
        if [ -n "$INTERFACE" ]; then
            echo "${yellow}** Starting tcpdump on $INTERFACE${white}, listening only $SERVER_IP and ICMP"
        else
            echo "${red}Unable to detect hijacked interface name by $WORKDIR/dumpService_stat.log - fatal - remove $TEMPDIR/$LOCATION by hand${white}"
            tput sgr0; exit
        fi

        echo "$TCPDUMPBIN -p -i $INTERFACE -U -w $PNAME-$SCRAMBLE-$i.pcap -s 0 tcp port 80 and host $SERVER_IP or icmp"
        $TCPDUMPBIN -p -i $INTERFACE -U -w $WORKDIR/$PNAME-$SCRAMBLE-$i.pcap -s 0 tcp port 80 and host $SERVER_IP or icmp >$WORKDIR/output.tcpdump 2>&1 &
        sleep 0.2
        echo "${yellow}** Starting curl to post/echo at $SERVER_ADDR ($SERVER_IP) under monitoring${white}"
        curl -s --retry 0 --max-time 10 -d "sparedata=$GENERATEDDATA" -o $WORKDIR/SPAREDATARECEIVED $SERVER >/dev/null 2>&1
        $SNIFFJOKECLIBIN info > $WORKDIR/dumpService_info.log
        $SNIFFJOKECLIBIN ttlmap > $WORKDIR/dumpService_ttlmap.log
        $SNIFFJOKECLIBIN quit > $WORKDIR/dumpService_quit.log
        if [ "$?" -eq 0 ]; then
            echo "${green}sniffjoke correctly closed${white}"
        else
            echo "${red}sniffjoke crashed during the test: very bad line to read :( remove $TEMPDIR/$LOCATION by hand${white}"
            tput sgr0; exit
        fi

        sleep 0.5
        killall -HUP tcpdump
    done;

    echo 0 > $TESTID/passed_count
    for i in `seq 1 $REPLICAn`;
    do
        WORKDIR=$TESTID/replica-${i}
        if [ -e "$WORKDIR/SPAREDATARECEIVED" ]; 
        then
            tr -d "\n" < $WORKDIR/SPAREDATARECEIVED > $WORKDIR/SPAREDATARECEIVED.clean
            CHECKSUM=`md5sum "$WORKDIR/SPAREDATARECEIVED.clean" | cut -b -32`
        else
            CHECKSUM="{unexistent-output-file}"

            # maybe the network has get an error
            isWorked=`grep "^0 packets captured" $WORKDIR/output.tcpdump`

            if [ -n "$isWorked" ]; then
                echo "${red}Something in the network is not going well, and will not be a SniffJoke fault"
                echo "${red}please, restart the test and remove the $TEMPDIR/$LOCATION"
                tput sgr0; exit;
            fi
        fi

        echo "orig:$VERIFYSUM recv:$CHECKSUM $TESTID $i" >> plugins-collected-feedback
        if [ $VERIFYSUM != $CHECKSUM ];
        then
            # the failed_hacks and the working_hacks are generated and treated in the same style
            # the follow are useful infos for debug
            echo "$VERIFYSUM vs $CHECKSUM from $PNAME-$SCRAMBLE replica $i" >> $TESTID/failed_info
        else
            echo $i > $TESTID/passed_count
        fi
    done

    if [ `cat $TESTID/passed_count` -eq $REPLICAn ];
    then
        echo $SCRAMBLE >> $PNAME/working_scrambles
        echo "${yellow}* FINISHED TEST $TESTID: ${green}TEST PASSED${white}\n"
        return 1
    else
        echo $SCRAMBLE >> $PNAME/failed_scrambles
        echo "${yellow}* FINISHED TEST $TESTID: ${red}TEST FAILED${white}\n"
        return 0
    fi
}

get_STATEDIR()
{

    locate_exists=`which locate`
    if [ -z "$locate_exists" ]; then
        locate_info
        tput sgr0; exit;
    fi

    marker=`locate THIS_IS_GENERIC | grep "var/sniffjoke"`
    if [ ! -z "$marker" ]; then
        GENERICDIR=`dirname $marker`
        LOCSDIR=`echo $GENERICDIR | sed -e's/generic//g'`
    else
        locate_info
        tput sgr0; exit;
    fi
}

compress_location_output()
{
    dFname="sjAlogs-$LOCATION.tar.bz2"
    tar -c -j -f $dFname --exclude='*DATA*' $TAR_EXCLUSION *
}

while getopts “hl:d:n:u:g:s:a:” OPTION
do
     case $OPTION in
         h)
             usage
             tput sgr0; exit 1
             ;;
         l)
             LOCATION=`echo $OPTARG | sed 's#/*$##'` #removing eventual(s) trailing slash
             ;;
         n)
             REPN=$OPTARG
             ;;
         u)
             USERNAME=$OPTARG
             ;;
# -d is became a semi-secret not more required options, because to avoid every system
# dependent requirement, now I'm using locate. this will cause some trouble in the developers,
# or in the other with some sniffjoke broked installation.
# the only solution, is keeping in your pants: http://www.youtube.com/watch?v=x-0FUCg7swU
         d)
             LOCSDIR=$OPTARG
             GENERICDIR="$LOCSDIR/generic"
             ;;
         g)
             GROUPNAME=$OPTARG
             ;;
# -s option is semi-secret, because I use them while testing a server side method 
# more complex than the post_echo.php
         s)
             SERVERURL=$OPTARG
             ;;
# -a MUST BE USED with -s
         a)
             SERVERADDR=$OPTARG
             ;;
         ?)
             usage
             tput sgr0; exit 1
             ;;
     esac
done

# every system dependend path, will be obtain here, and checked below
if [ -z "$LOCSDIR" ]; then
    get_STATEDIR
fi

TEMPDIR="/tmp"
cd $TEMPDIR

SNIFFJOKEBIN=`which sniffjoke`
if [ -z "$SNIFFJOKEBIN" ]; then
    echo "\n${red}"
    echo "\"which sniffjoke\" has found nothing"
    echo "Are sniffjoke installed with the name \"sniffjoke\" ?"
    echo "${white}"
    tput sgr0; exit;
fi

TCPDUMPBIN=`which tcpdump`
if [ -z "$TCPDUMPBIN" ]; then
    echo "\n${red}"
    echo "\"which tcpdump\" has found nothing"
    echo "tcpdump is required by this testing script, because the traffic need to be captured an analyzed"
    # if you're asking "where are the .pcap(s) analyzed ?" "in sj-iptcpopt-probe"
    echo "${white}"
    tput sgr0; exit;
fi

CURLBIN=`which curl`
if [ -z "$CURLBIN" ]; then
    echo "\n${red}"
    echo "\"which curl\" has found nothing"
    echo "curl is required by this testing script, because are performed some HTML POSTs"
    echo "${white}"
    tput sgr0; exit;
fi

SNIFFJOKECLIBIN=`which sniffjokectl`
if [ -z "$SNIFFJOKECLIBIN" ]; then
    echo "\n${red}"
    echo "\"which sniffjokectl\" has found nothing"
    echo "Are sniffjoke installed with the name \"sniffjokectl\" ?"
    echo "${white}"
    tput sgr0; exit;
fi

IPTCPPROBE=`which sj-iptcpopt-probe`
if [ -z "$IPTCPPROBE" ]; then
    echo "\n${red}"
    echo "\"which sj-iptcpopt-probe\" has found nothing"
    echo "Are sniffjoke installed correctly ? sj-iptcpopt-probe and sniffjoke-autotest are installed together.."
    echo "${white}"
    tput sgr0; exit;
fi

USERID=`id -u`
if [ $USERID != "0" ]; then
    echo "- Error, only root should run $0"
    tput sgr0; exit;
fi

if [ -z $LOCATION ]; then
    usage
    echo "\n${red}"
    echo "it's required a LOCATION name, eg: office, home, nickhome, starbucks..."
    echo "sniffjoke-autotest will generate the best plugins-enabled.conf usable in this environment"
    echo "at the end of the tests (that include continuos restarting of sniffjoke with different options)"
    echo "will be created a new directory describing your location. after you will customize the options"
    echo "${white}"
    tput sgr0; exit;
fi

if [ ! -d $LOCSDIR ]; then
    usage
    echo "\n${red}"
    echo "Bad issue: $LOCSDIR is expected to be a directory"
    echo "(should became from -d option or from internal usage of 'locate') "
    echo "${white}"
    tput sgr0; exit;
fi

if [ -z $USERNAME ]; then
    USERNAME="nobody"
fi

if [ -z $GROUPNAME ]; then
    group_check
fi
# user group privilege downgrade, this variable will be passed to ipopt testing
UGPD="--user $USERNAME --group $GROUPNAME"

if [ ! -d $GENERICDIR ]; then
    usage
    echo "\n${red}"
    echo "options \"-d\" invalid directory: we are looking for the path containing 'generic/'"
    echo "sniffjoke-autotest create at the given \"-d\", the new '$LOCATION/' copying some files from 'generic/'"
    echo "${white}"
    tput sgr0; exit;
fi

if [ -d $LOCSDIR/$LOCATION ]; then
    echo "\n${red}"
    echo "error: $LOCSDIR/$LOCATION directory already present, remove by hand: don't keep old location, nor two location with the same name :P"
    tput sgr0; exit;
fi

if [ -d $TEMPDIR/$LOCATION ]; then
    usage
    echo "\n${red}"
    echo "- error: $TEMPDIR/$LOCATION directory already present"
    echo "${white}"
    tput sgr0; exit;
else
    mkdir $TEMPDIR/$LOCATION
fi

cd $TEMPDIR/$LOCATION

echo "* Stopping possible running sniffjoke ($SNIFFJOKECLIBIN quit)"
$SNIFFJOKECLIBIN quit >/dev/null 2>&1

ln -s $GENERICDIR . 

# dumping of useful information when sniffjoke doesn't run and you ask to the dev
ifconfig >> LAN.info
route -n >> LAN.info
iptables -nL >> LAN.info
uname -a >> LAN.info

if [ -z "$SERVERURL" ]; then
    trusted_server_contact

    FILEURL="http://www.delirandom.net/sjA/autotest.php?v=$VERSION"
    echo "* retrivering multi-OS testing server list ($FILEURL)"
    SERVERFILE="sj-server.info"

    $CURLBIN -o $SERVERFILE $FILEURL  >/dev/null 2>&1
    if ! [ -e $SERVERFILE ]; 
    then
        echo "\n${red}"
        echo "- unable to retriver $SERVERFILE with curl from [$FILEURL]"
        echo "${white}"
        tput sgr0; exit;
    fi
    if [ $GNUPGTRUST == "YEP" ]; then
        $GPGBIN $KEYRINGOPT --verify $SERVERFILE >/dev/null 2>&1
        if [ "$?" != "0" ]; then
            echo "${red}Invalid GPG signature of received file! its a dangerous anomaly."
            echo "${red}Check by hand, and if something don't seem plain to you, give ^c and asks to your friends using SniffJoke"
            echo "${blue}Received file:"
            tput sgr0;
            cat $SERVERFILE
            echo "${red}If you want proceed, press return"
            read
        else
            echo ${green}Checked signature by gpg key: valid file received
        fi
    else
        echo "${yellow}Received $SERVERFILE, but without GnuPG could not be verified"
    fi

    # these are the variable retriverable from the server 
    SERVER=`grep  "TESTSRV=" $SERVERFILE | cut -b 9-`
    MESSAGE=`grep "MESSAGE=" $SERVERFILE | cut -b 9-`
    RESULTS=`grep "RESULTS=" $SERVERFILE | cut -b 9-`
    SERVER_IP=`grep  "IPTEST=" $SERVERFILE | cut -b 8-`
    STOP=`grep "STOP=" $SERVERFILE | cut -b 6- | tr -c -d [:alpha:]`
else
    # this is kind of easter egg, but, without cow super power
    echo "${blue} hello ${yellow}yellow ${blue}daddy! http://shinysushi.deviantart.com/art/Asari-Logic-194960943"
    SERVER=$SERVERURL
    SERVER_IP=$SERVERADDR
fi

if [ ! -z "$MESSAGE" ]; then
    echo "${blue}Message retrivered from the SniffJoke autotest service:"
    echo "* --------- ----- --- -- -"
    echo "${green}$MESSAGE ${blue}"
    echo "* --------- ----- --- -- -"
    echo "Message finished"

    if [ $STOP == "YES" ]; then
        echo "\n${green}do you want continue ? if not, give ^C and remove $TEMPDIR/$LOCATION, otherwise, press return"
        read
    fi
fi

echo "${yellow}+ Starting SniffJoke hacks test"

# uh remember coder: the http port www.umpalumpa.net:803213 is NOT SUPPORTED
SERVER_ADDR=`echo $SERVER | sed -e's/.*\/\///' | sed -e's/\/.*//'`

if [ -z $SERVER_ADDR ] || [ -z $SERVER_IP ]; then
    echo "${red}Server Address and Server IP lacking: if you are not using -a or -s, there are some problem in delirandom"
    echo "Incidentally, delirandom is, at the moment, the single point of failure of this project"
    tput sgr0; exit;
fi

# oh yeah pippa middleton, this line is for you!!1:
echo "${green} remote server IP '$SERVER_IP' and HTTP URL '$SERVER_ADDR'"

PLUGINLIST="plugins-testsuite"
dump_plugin_file
PLUGIN_NUMBER=`wc -l < $PLUGINLIST`

# generate the SPAREDATA file to send
GENERATEDFILE="SPAREDATA_plugin"
# the number '6' is not used in the test because sniffjoke, when runned
# in debug mode (--debug 6) instead of filling the random segment of data
# inject with random data, use the number '6'. Is useful when debugging 
# an hack.
seq 1000 9000 | tr -d [:cntrl:] | sed -e's/6/111/g' | strings | tr -d "\n" > $GENERATEDFILE
GENERATEDDATA=`cat $GENERATEDFILE`
VERIFYSUM=`md5sum $GENERATEDFILE | cut -b -32`

# OK GUYS, SINCE HERE WE'D SETUP THE ENVIRONMENT, NOW START THE THREE SECTION Of TESTS:
# TEST 1) a simple plain connection, useful for the first traceroute and general checkup
# TEST 2) testing of every IP/TCP header options and conseguencial generation of "iptcp-options.conf"
# TEST 3) testing of every scramble+plugin combination, generation of "plugins-enabled.conf"
# at the end, you have all the location specific files required for a safe usage of sniffjoke

# TEST 1
PLUGIN="segmentation,INNOCENT"
start_test 1
if [ ! $? ]; then
    echo "${red} the simplest test has failed, something dirty don't work in your network"
    tput sgr0; exit;
fi
firstsimple=$TEMPDIR/$LOCATION/firstsimple
mv $TEMPDIR/$LOCATION/segmentation/INNOCENT/replica-1 $firstsimple

# TEST 2
# (now in $firstsimple/ttlfocusmap.bin is cached the traceroute)
$IPTCPPROBE -w "$TEMPDIR/$LOCATION" -u "$SERVER" -n $USERNAME -g $GROUPNAME -i $SERVER_IP

# TEST 3
# (now in $TEMPDIR/$LOCATION/iptcp-options.conf there are the correct usage for this location)
for PLUGNDX in `seq 1 $PLUGIN_NUMBER`; do
    PLUGIN=`head -$PLUGNDX $PLUGINLIST | tail -1`

    # those test need to be fixed or be used only where my test script will be hosted
    echo "${blue}Starting test vs Linux environment: ($SERVER_ADDR, $SERVER_IP)"
    start_test $REPN
done

# Parsing & formatting the results of TEST 3
PeL="plugins-enabled.conf"
echo "# this is an autogenerated file by sniffjoke-autotest " > $PeL
echo "# wheneven you change the network router, provider or some malfunction is detected" >> $PeL
echo "# you are invited to regenerate this file" >> $PeL
echo "# this plugins-enabled.conf \"$VERSION\" its for location: $LOCATION using $SERVER_IP" >> $PeL

success_count=0
TAR_EXCLUSION=""
for PLUGIN in `ls */working_scrambles 2>/dev/null | sed -e 's/\/working_scrambles//'` ; do
    SCRAMBLES=`cat $PLUGIN/working_scrambles | tr " " "," | tr [:cntrl:] ","`
    echo "$PLUGIN,$SCRAMBLES" | sed -es/,\$// >> $PeL
    success_count=$(($success_count+1));

    for SCRAMBLE in `cat $PLUGIN/working_scrambles`; do
        TAR_EXCLUSION=$TAR_EXCLUSION" --exclude=$PLUGIN/$SCRAMBLE"
    done
done

echo "\n# follow the hacks+scramble that don't pass the sniffjoke-autotest in environment \"$LOCATION\"\n" >> $PeL
failure_count=0
for PLUGIN in `ls */failed_scrambles 2>/dev/null | sed -e 's/\/failed_scrambles//'` ; do
    SCRAMBLES=`cat $PLUGIN/failed_scrambles | tr " " "," | tr [:cntrl:] ","`
    echo "# $PLUGIN,$SCRAMBLES" | sed -es/,\$// >> $PeL
    failure_count=$(($failure_count+1));
done

now=`date`
echo "\n# Generated in date: $now\n" >> $PeL

echo "${yellow}FINISHED!\n"
echo " ${red} $failure_count combinations of hack+scramble have not worked"
echo " ${green} $success_count combinations of hack+scramble have worked correctly${white}"

if [ $failure_count -ge 6 ]; then
    echo "\n"
    echo " ${red} Several combinations of hack+scramble have not worked: sometime has worked put an MTU lower, eg: ifconfig <interface> mtu 1300"
    echo "\n"
fi

chmod 444 plugins-enabled.conf

DESTINATION=$LOCSDIR/$LOCATION
mkdir $DESTINATION

cp $GENERICDIR/port-aggressivity.conf $DESTINATION 
cp $GENERICDIR/sniffjoke-service.conf $DESTINATION
cp $TEMPDIR/$LOCATION/iptcp-options.conf $DESTINATION
cp plugins-enabled.conf $DESTINATION/plugins-enabled.conf

echo "\n${yellow}* sniffjoke-autotest has dumped $TEMPDIR/$LOCATION/plugins-enabled.conf"
echo "* that conf has been copyed in $DESTINATION with the other default configuration file."
echo "* now, when you are using internet in this network environment, use sniffjoke with the option --location $LOCATION${white}"

if [ ! -z "$SERVERURL" ]; then
    echo "${blue} compressig data and quitting: commit data not provided in hand usage"
    compress_location_output
    tput sgr0; exit;
fi

tput sgr0
echo "if you want to: 1) have an easyest support 2) have an automatized analysis of your network capability 3) contribute in sniffjoke"
echo "automatically this script will send to the testing server some data collected in this test. what data are send:"
echo "  networking/system information (routing table, kernel configuration)"
echo "  log files of sniffjoke execution, warning: some IP address of your present connection may result (obviously, not the data)"
echo "  traffic monitor of the testing session and ICMP error traffic"
echo "  only the tests related the plugins that have failed"
echo "${green}the data are intended to be used for debug and optimization only, and you could delete your submission when you wish."
echo "submission will be do to \"$RESULTS\""
tput sgr0
echo "if you want to send, write: ${green}OK"
read YESORNOT 

if [ "$YESORNOT" == "OK" ]; then
    compress_location_output
    echo "${green} sending of the file... to $RESULTS"
    output_put="$TEMPDIR/$LOCATION/HTTP_put.out"
    $CURLBIN -o $output_put -T $dFname "$RESULTS?v=$VERSION"
    if [ -e "$output_put" ]; then
        MESSAGE=`grep "MESSAGE=" $output_put | cut -b 9-`
        URL=`grep "URL=" $output_put | cut -b 5-`
        echo "${blue} message received from the server:"
        echo "* --------- ----- --- -- -"
        echo "${green}$MESSAGE"
        echo "${green}$URL"
    else
        echo "${red}Error in uploading: operation fail"
    fi
else
    echo "freedom of choice imply that my script must accept '$YESORNOT' as different of 'OK'. no upload for this time :( amen"
fi

# clearing gay colors
tput sgr0

