#!/bin/bash

# handler_quickscope - converts a quickscope into a quotation
#
# 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
#                            John Sinteur
#
#    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.3
SAXON=/usr/local/bin/saxon/saxon9he.jar
TEMPLOC=$(mktemp -d)


# These variables should be set environment-specific
[ -z $GITSERVER ] && GITSERVER=gitlab.local
[ -z $NAMESPACE ] && NAMESPACE=ros

# Read standard 'command line' variables
[[ ! -z $1 ]] && REPO=$1
[[ ! -z $2 ]] && NAMESPACE=$2
[[ ! -z $3 ]] && BRANCH=$3 || BRANCH=master

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
}

# Clones repo using global (!) variables - v0.2
clone_repo() {
    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}/${REPO}"
        exit 1
    else
        cd $REPO
    fi
}

# Preflight checks using global (!) variables
preflight_checks() {
    if [ -z $REPO ]; then
        echo "Usage: quickscope REPOSITORY [NAMESPACE]"
        exit
    fi
    if [ ! -f $SAXON ]; then
        echo "[-] this script needs saxon ($SAXON)"
    fi
}

convert_quickscope() {
    if [ ! -f $TEMPLOC/$REPO/source/quickscope.xml ] || [ ! -f $TEMPLOC/$REPO/xslt/qs2offerte.xsl ]; then
        echo "[-] missing necessary pentext framework files"
        exit 1
    fi
    java -jar $SAXON -s:$TEMPLOC/$REPO/source/quickscope.xml -xsl:$TEMPLOC/$REPO/xslt/qs2offerte.xsl -o:$TEMPLOC/$REPO/source/offerte.xml
    if [ ! -f $TEMPLOC/$REPO/source/offerte.xml ]; then
        echo "[-] failed to parse quote"
        exit
    fi
}

add_to_repo() {
    git add source/offerte.xml &>/dev/null
    git commit -q -m "Created quickscope using ChatOps" &>/dev/null
    git push -q >/dev/null
}

preflight_checks
echo "quickscope v${VERSION} - Rockin' and scoping'..."
clone_repo
convert_quickscope
add_to_repo
echo "[+] listo!"
exit 0
