#!/bin/bash
set -e

# Variables
OPENSSL_VERSION="1.1.1s"
PYTHON_VERSION="3.8.10"
SRC_DIR="/usr/src"

echo "Starting installation of OpenSSL $OPENSSL_VERSION and Python $PYTHON_VERSION..."

# Install prerequisites (adjust based on your Debian version)
apt-get update
apt-get install -y build-essential wget libffi-dev libssl-dev zlib1g-dev

# Download and install OpenSSL
cd $SRC_DIR

if [ -d "openssl-$OPENSSL_VERSION" ]; then
    echo "Removing existing openssl-$OPENSSL_VERSION folder"
    rm -rf "openssl-$OPENSSL_VERSION"
fi

echo "Downloading OpenSSL $OPENSSL_VERSION..."
wget "https://www.openssl.org/source/openssl-$OPENSSL_VERSION.tar.gz"
tar -xzf "openssl-$OPENSSL_VERSION.tar.gz"
cd "openssl-$OPENSSL_VERSION"

echo "Configuring OpenSSL..."
./config --prefix=/usr/local/ssl --openssldir=/usr/local/ssl shared zlib
make -j$(nproc)
make install

echo "/usr/local/ssl/lib" > /etc/ld.so.conf.d/openssl-$OPENSSL_VERSION.conf
ldconfig

# Download and install Python
cd $SRC_DIR

if [ -d "Python-$PYTHON_VERSION" ]; then
    echo "Removing existing Python-$PYTHON_VERSION folder"
    rm -rf "Python-$PYTHON_VERSION"
fi

echo "Downloading Python $PYTHON_VERSION..."
wget "https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tgz"
tar -xzf "Python-$PYTHON_VERSION.tgz"
cd "Python-$PYTHON_VERSION"

echo "Configuring Python build with OpenSSL support..."
./configure --with-openssl=/usr/local/ssl --enable-optimizations
make -j$(nproc)
make install

echo "Verifying OpenSSL version used by Python..."
python3.8 -c "import ssl; print('Python OpenSSL version:', ssl.OPENSSL_VERSION)"

echo "Installation complete."

