#!/bin/bash

# test_pentext - tests the PenText toolchain
#
# This script is part of the PenText framework
#                            https://pentext.org
#
#    Copyright (C) 2016      Radically Open Security
#                            https://www.radicallyopensecurity.com
#
#                 Author(s): Peter Mosmans
#
#    This program 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 3 of the License, or
#    (at your option) any later version.


VERSION=0.6
DOCBUILDER=/usr/local/bin/docbuilder.py
VALIDATOR=/usr/local/bin/validate_report.py
SAXON=/usr/local/bin/saxon/saxon9he.jar

# These variables should be set environment-specific
[ -z $GITLABCLI ] && GITLABCLI=gitlab
[ -z $GITSERVER ] && GITSERVER=gitlab.local
[ -z $GITWEB ] && GITWEB=https://$GITSERVER
[ -z $NAMESPACE ] && NAMESPACE=ros
[ -z $NAMESPACEID ] && NAMESPACEID=1
[ -z $PENTEXTREPO ] && PENTEXTREPO=https://github.com/radicallyopensecurity/pentext

TEMPLOC=$(mktemp -d)
BRANCH=master
reponame=test-pentext-$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)
pentext=$(echo $PENTEXTREPO|awk -F '/' '{print $5}')
# Read standard 'command line' variables
[[ ! -z $1 ]] && REPO=$1
# Reading parms is a bit ugly, shifting parms or actually using getopt would be nicer
if [[ ! -z $2 ]]; then
    if [[ ! $2 == -* ]]; then
        NAMESPACE=$2
    else
        PARMS=$2
    fi
fi
if [[ ! -z $3 ]]; then
    if [[ ! $3 == -* ]]; then
        BRANCH=$3
    else
        PARMS="$PARMS $3"
    fi
fi
if [[ $# -ge 4 ]]; then
    shift 3
    PARMS="$PARMS $@"
fi

trap cleanup EXIT QUIT

# Make sure that the temporary files are always removed
cleanup() {
    trap '' EXIT INT QUIT
    [ -d $TEMPLOC ] && rm -rf $TEMPLOC &>/dev/null

    exit
}

# As quote used to be called offerte or offer,
# this function retains backward compatibility - v0.2
backwards_compatible() {
    if [[ $TARGET == "quote" ]] && [ ! -f $TARGET.xml ]; then
        TARGET="offerte"
    fi
}

setup_repo() {
    echo "[*] testing gitlab command line interface..."
    REPO=${reponame,,} # lowercase, but of course
    project_id=$($GITLABCLI project create --name $REPO --namespace $NAMESPACEID --issues-enabled true --wiki-enabled true --snippets-enabled true --wall-enabled true --merge-requests-enabled true| awk '/id:/{print $2}')
    if [ ! -z $project_id ]; then
        echo "[+] successfully created test gitlab project with id ${project_id}"
    else
        echo "[-] could not create repo $reponame - is the .python-gitlab.cfg configuration corrent ?"
        exit 1
    fi
}

# Clones repo using global (!) variables - v0.3
clone_repo() {
    echo "[*] testing gitlab SSH access using ssh://git@${GITSERVER}/${NAMESPACE}..."
    pushd $TEMPLOC 1>/dev/null
    git clone --depth=1 -q ssh://git@${GITSERVER}/${NAMESPACE}/$REPO.git &>/dev/null
    if [ ! -d $TEMPLOC/$REPO ]; then
        echo "[-] could not clone repo ${NAMESPACE}/$reponame - is the namespace correct ?"
        exit 1
    else
        echo "[+] successfully cloned repo using namespace ${NAMESPACE}"
    fi
    cd $TEMPLOC/$REPO
}

# Preflight checks
preflight_checks() {
    echo "The following variables will be used: "
    echo "DOCBUILDER=$DOCBUILDER  (location of docbuilder.py)"
    echo "GITLABCLI=$GITLABCLI  (command line gitlab interface)"
    echo "GITSERVER=$GITSERVER  (git server)"
    echo "GITWEB=$GITWEB  (webinterface of git server)"
    echo "NAMESPACE=$NAMESPACE  (namespace of repositories)"
    echo "NAMESPACEID=$NAMESPACEID  (namespace ID of repositories)"
    echo "PENTEXTREPO=$PENTEXTREPO  (location of pentext repo)"
    echo "SAXON=$SAXON  (saxon binary)"
    echo "VALIDATOR=$VALIDATOR  (location of validate_report.py)"
    echo "[*] testing binaries..."
    [ ! -f $VALIDATOR ] && echo "[-] validate_report.py ($VALIDATOR) is missing (necessary for validate)"
    [ ! -f $DOCBUILDER ] && echo "[-] docbuilder.py ($DOCBUILDER) is missing (necessary for build)"
    [ ! -f $SAXON ] && echo "[-] saxon ($SAXON) is missing (necessary for invoice)"
    which java &> /dev/null || echo "[-] java is missing (necessary for saxon)"
    if ! which $GITLABCLI &>/dev/null && [ ! -f $GITLABCLI ]; then
        echo "[-] gitlab ($GITLABCLI) is missing, required for startquote and startpentest"
        exit 1
    fi
}

add_to_repo() {
    echo "[*] testing add to repo"
    echo "commit test" > testcommit
    git add testcommit
    git commit -q -m "test_pentext testcommit"
    git push -q
    if [ $? -ne 0 ]; then
        echo "[-] failed adding stuff to repo"
    fi
}

delete_repo() {
    if [ ! -z $project_id ]; then
        $GITLABCLI project delete --id $project_id &>/dev/null
        if [ $? -eq 0 ]; then
            echo "[+] successfully deleted testproject $project_id"
        else
            echo "[-] hmmm... failed deleting testproject $project_id"
            exit 1
        fi
    fi
}

clone_pentext() {
    echo "[*] testing access to PenText repo $PENTEXTREPO..."
    pushd $TEMPLOC 1>/dev/null
    git clone --depth=1 $PENTEXTREPO &>/dev/null
    popd 1>/dev/null

    if [ ! -d $TEMPLOC/$pentext ]; then
        echo "[-] could not clone repo $TEMPLATEREPO..."
        exit 1
    fi
}


# preflight_checks
echo "test_pentext v$VERSION - Testing the PenText toolchain"
preflight_checks
setup_repo
clone_repo
add_to_repo
delete_repo
clone_pentext
echo "[+] all tests successful. Good to go!"
