#!/bin/bash
#
#  get_logs.sh: Script to collect the vRO, server and configurator
#  logs from the vra appliance
#

# Setup default options
default_opts()
{
    PASSWD='pwd'
    PASSWD_ARG=0
    UNCOMPRESS=0
    LOCAL=0
    SETUP=0
}

usage()
{
    echo "Usage: " $(basename $0) " [-u] [-l] [-p <password>] [-s <vra_setup>]"
    echo "       -l    run locally in vra"
    echo "       -p    password (can be skipped for default passwd)"
    echo "       -s    vra_setup"
    echo "       -u    un-compress (ie., don't create .tar.gz file)"
    echo " Examples: "
    echo " 1) Running the script locally in vra"
    echo "    cd /root;./get_logs.sh -l"  
    echo " 1) Running the script in an external linux/unix system"
    echo "    ./get_logs.sh -p <****> -s myvra-71"  
    exit 1
}

# Parse commandline options
parse_opts()
{
    default_opts

    while getopts "lp:s:hu" OPT
    do
        case ${OPT} in
	l)
            LOCAL=1
	    ;;
	s)
            SETUP=1
            SETUP_NAME=$OPTARG
            ;;
        p)
            PASSWD_ARG=1
	    PASSWD=$OPTARG
            ;;
        u)
            UNCOMPRESS=1
            ;;
        h | \? | *)
	    usage
	    ;;
        esac
    done
}

# main
parse_opts "$@"


if [ ${LOCAL} -eq 0 ]; then
    if [ ${SETUP} -eq 0 ]; then
	usage
    fi
    if [ `which sshpass | grep sshpass | wc -l` -eq 0 ]; then
	echo "sshpass not found! Please install sshpass utility"
	exit -1
    fi

    if [ `which scp | grep scp | wc -l` -eq 0 ]; then
	echo "scp not found! Please install secure cp (scp) utility"
	exit -1
    fi

fi


curdir=$(pwd)
echo "Copying VRA logs from $1 to $curdir"

echo "Passwd is ", ${PASSWD}
echo "Setup is", ${SETUP_NAME}

if [ ${UNCOMPRESS} -eq 0 ]; then
    temp=$(mktemp -d /tmp/vra.XXXX) && cd $temp
else
    temp=${SETUP_NAME}-logs && mkdir -p $temp && cd $temp
fi

mkdir -p logs/configuration
mkdir -p logs/app-server

echo "Copying Configuration Logs"

if [ ${LOCAL} -eq 0 ]; then
    sshpass -p ${PASSWD} scp root@${SETUP_NAME}:/var/lib/vco/configuration/logs/catalina.out* ./logs/configuration
else
    \cp -f /var/lib/vco/configuration/logs/catalina.out* ./logs/configuration
fi
    
echo "Copying App Server Logs"
if [ ${LOCAL} -eq 0 ]; then
    sshpass -p ${PASSWD} scp root@${SETUP_NAME}:/var/lib/vco/app-server/logs/{catalina.out*,server.log*\} ./logs/app-server
else
    \cp -f /var/lib/vco/app-server/logs/{catalina.out*,server.log*} ./logs/app-server
fi


if [ ${UNCOMPRESS} -eq 0 ]; then
    echo "Compressing Logs"
    filename=vra_logs_$(date +"%Y%m%d%H%M").tar.gz
    tar -czvf $filename logs/
    echo "Logs saved in $filename"
    mv $filename $curdir
    cd $curdir
    echo "Removing $temp"
    echo "rm -rf $temp"
fi
