cwd=$PWD

compile () {
  if [ ! -f $cwd/$1/apps/openssl ]; then
    echo "[+] Compile debug mode version of $1"
    wget https://github.com/openssl/openssl/archive/refs/tags/$1.zip
    unzip $1.zip
    mv openssl-$1 $1
    cd $1
    ./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 "[+] $1 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*
}

clean () { 
  rm -rf openssl*
  clean_server
}

run_server () {
  compile openssl-3.0.7
  build_server
  cd $cwd/server
  ./run_server.sh
}

run_vuln_client () {
  compile openssl-3.0.6
  cd $cwd/client
  ./gdb_client.sh
}

if (test $# -eq 1); then
  if (test $1 = "clean"); then
    clean
  elif (test $1 = "build_server"); then
    build_server
  elif (test $1 = "clean_server"); then
    clean_server
  elif (test $1 = "run_vuln_client"); then
    run_vuln_client
  elif (test $1 = "run_server"); then
    run_server
  fi
elif ((test $# -eq 2) && (test $1 = "compile")); then
    compile $2
fi
