cwd=$PWD

compile () {
  if [ ! -f $cwd/openssl/apps/openssl ]; then
    echo "[+] Compile debug mode version of OpenSSL 3.0.6"
    wget https://github.com/openssl/openssl/archive/refs/tags/openssl-3.0.6.zip
    unzip openssl-3.0.6.zip
    mv openssl-openssl-3.0.6 openssl
    cd openssl
    ./Configure no-tests -debug -static && sed -i 's/^CFLAGS=.*/CFLAGS=-Wall -Og -g3 -fno-inline-functions -fdump-rtl-expand/' Makefile && make clean && make -j`nproc`
  else
    echo "[+] OpenSSL 3.0.6 already compiled: SKIP"
  fi
}

build_server () {
  cd $cwd/server
  ./gen.sh
}

clean_server () {
  echo "cleaning Server certificates"
  rm -rf $cwd/server/certs $cwd/server/private $cwd/server/index.* $cwd/server/serial*
}

build_client () {
  cd $cwd/client
  ./gen.sh
}

clean_client () {
  echo "cleaning Server certificates"
  rm -rf $cwd/client/certs $cwd/client/private $cwd/client/index.* $cwd/client/serial* 
}

clean () { 
  rm -rf openssl*
  clean_client
  clean_server
}

all () {
  compile
  build_server
  build_client
}

run_vuln_server () {
  compile
  build_server
  build_client
  echo -e "\n===================================================================================\n"
  echo -e "                     RUN MALICIOUS CLIENT\n"
  echo "Send crafted certificate with the following command in another term:"
  echo "cd $cwd/client && ./run_client.sh" 
  echo -e "\n===================================================================================\n"
  cd $cwd/server
  ./gdb_vuln_server.sh
}

if (test $# -eq 1); then
  if (test $1 = "clean"); then
    clean
  elif (test $1 = "compile"); then
    compile
  elif (test $1 = "build_server"); then
    build_server
  elif (test $1 = "build_client"); then
    build_client
  elif (test $1 = "clean_server"); then
    clean_server
  elif (test $1 = "clean_client"); then
    clean_client
  elif (test $1 = "all"); then
    all
  elif (test $1 = "run_vuln_server"); then
    run_vuln_server
  fi
fi
