#!/bin/bash

set -ue

REINSTALL=0

while getopts -- "-:" a ; do
  case "${a}" in
    -)
    case "${OPTARG}" in
      reinstall)
        REINSTALL=1
        ;;
      *)
        echo "Unknown long option ${OPTARG}" >/dev/stderr
        exit 1
        ;;
    esac
  esac
done

shift $(($OPTIND-1))
echo $*

if [ $# -ne 1 ] ; then
  echo "Usage: ${0} <tool>" >/dev/stderr
  exit 1
fi
TOOL=${1}

function install_pkgs {
  if [ `id -u` -ne "0" ] ; then
    sudo apt-get -y install $* || (
      echo "Unable to install packages, please ensure these are installed." >/dev/stderr
      echo $*
      false )
    return 0
  fi
  apt-get -y install $*
}

DESTDIR="${HOME}/tools/${TOOL}"

if [ -d ${DESTDIR} ] ; then
  if [ ${REINSTALL} -eq 1 ] ; then
    rm -ri ${DESTDIR}
  else
    echo "${DESTDIR} exists but not reinstalling." >/dev/stderr
    exit 1
  fi
fi

case ${TOOL} in
  john)
    install_pkgs libssl-dev git build-essential yasm libgmp-dev libpcap-dev \
      pkg-config libbz2-dev libopenmpi-dev openmpi-bin libnss3-dev \
      libkrb5-dev libgmp-dev
    jtemp=`mktemp -d`
    git clone https://github.com/magnumripper/JohnTheRipper.git ${jtemp}/john
    cd ${jtemp}/john/src
    ./configure && make -sj2
    mkdir -p ${DESTDIR}
    cp -r ${jtemp}/john/run/* ${DESTDIR}
    rm -rf ${jtemp}
    # Persistent files
    mkdir -p ${HOME}/.john
    touch ${HOME}/.john/john.pot
    ln -sf ${HOME}/.john/* ${DESTDIR}
    ;;
  wordlists)
    mkdir -p ${DESTDIR}
    wget -q -O ${DESTDIR}/rockyou.txt.bz2 \
      http://downloads.skullsecurity.org/passwords/rockyou.txt.bz2
    bunzip2 ${DESTDIR}/rockyou.txt.bz2
    wget -q -O ${DESTDIR}/phpbb.txt.bz2 \
      http://downloads.skullsecurity.org/passwords/phpbb.txt.bz2
    bunzip2 ${DESTDIR}/phpbb.txt.bz2
    wget -q -O ${DESTDIR}/hak5.txt.bz2 \
      http://downloads.skullsecurity.org/passwords/hak5.txt.bz2
    bunzip2 ${DESTDIR}/hak5.txt.bz2
    ;;
  *)
    echo "Unknown tool: ${TOOL}" >/dev/stderr
    exit 1
    ;;
esac
