#!/bin/bash
set -e

if [ "$#" -ne 2 ]; then
    echo "need 2 parameters : python_version and openssl_version"
    echo "example : 3.10.19 3.5.4"
    exit
fi

python_version="$1"
openssl_version="$2"

apt-get update -y
apt-get install debootstrap -y

rm -Rf /root/python_builddir/

# we need to specify http url instead of https because of out of date certificate authority 
# in buster by default and add security updates repo, otherwise superseeded package don't have
# the most recent supported gpg key signature
debootstrap  buster /root/python_builddir/ http://archive.debian.org/debian
cat << EOF > /root/python_builddir/etc/apt/sources.list
deb http://archive.debian.org/debian buster main
 
EOF

chroot /root/python_builddir/ bash -c "LANG=C apt-get update"
#debootstrap  jammy /root/python_builddir/

#chroot /root/python_builddir/ bash -c "LANG=C apt-get install software-properties-common -y"
#chroot /root/python_builddir/ bash -c "LANG=C add-apt-repository universe -y "
chroot /root/python_builddir/ bash -c "LANG=C apt-get install -y autoconf rsync automake libtool pkg-config libpng-dev libfreetype6-dev build-essential libbz2-dev libreadline-dev zlib1g-dev libsqlite3-dev tk-dev libgdm-dev patchelf patch byacc wget locales software-properties-common liblzma-dev lzma libsqlite3-0"

chmod 755 step2_compile_python_in_debootstrap.sh
cp step2_compile_python_in_debootstrap.sh /root/python_builddir/root/step2_compile_python_in_debootstrap.sh

wget https://github.com/openssl/openssl/releases/download/openssl-${openssl_version}/openssl-${openssl_version}.tar.gz --directory-prefix=/root/python_builddir/root/
wget https://www.python.org/ftp/python/${python_version}/Python-${python_version}.tgz --directory-prefix=/root/python_builddir/root/
wget https://kerberos.org/dist/krb5/1.22/krb5-1.22.1.tar.gz --directory-prefix=/root/python_builddir/root/
wget https://github.com/OpenSC/libp11/archive/refs/tags/libp11-0.4.16.tar.gz --directory-prefix=/root/python_builddir/root/
wget https://ftp.postgresql.org/pub/source/v15.14/postgresql-15.14.tar.bz2 --directory-prefix=/root/python_builddir/root/
wget https://github.com/libffi/libffi/releases/download/v3.5.2/libffi-3.5.2.tar.gz --directory-prefix=/root/python_builddir/root/
wget https://ftp.gnu.org/gnu/readline/readline-8.3.tar.gz --directory-prefix=/root/python_builddir/root/
wget https://ftp.gnu.org/pub/gnu/gdbm/gdbm-1.26.tar.gz --directory-prefix=/root/python_builddir/root/
wget https://github.com/thkukuk/libnsl/releases/download/v2.0.1/libnsl-2.0.1.tar.xz --directory-prefix=/root/python_builddir/root/
wget https://www.sqlite.org/src/tarball/sqlite-product-3510000.tar.gz -O /root/python_builddir/root/sqlite.tar.gz
wget https://github.com/besser82/libxcrypt/releases/download/v4.5.1/libxcrypt-4.5.1.tar.xz --directory-prefix=/root/python_builddir/root/

chroot /root/python_builddir bash -c "LANG=C /root/step2_compile_python_in_debootstrap.sh ${python_version} ${openssl_version}"
