#!/bin/bash

# Required packages to compile:
#
# libffi-devel

# Setup the environment
. /etc/profile

set -o errexit
set -o nounset

# Setup the versions
MAJOR_VERSION=3.14
VERSION=3.14.5

# Concurrent make
JOBS="$(expr "$(getconf _NPROCESSORS_ONLN)" + 1)"

# Create temp build directory
TMPDIR="`mktemp -d /tmp/python-${MAJOR_VERSION}-build.XXXXXXXXXX`"

# Untar the source code
tar -xJ -C "${TMPDIR}" -f "/opt/python-$MAJOR_VERSION/src/Python-$VERSION.tar.xz"

# Compile
cd "${TMPDIR}/Python-$VERSION"
./configure \
    --srcdir="${TMPDIR}/Python-$VERSION" \
    --prefix="/opt/python-$MAJOR_VERSION" \
    --enable-optimizations \
    --without-remote-debug
make -j "$JOBS"

# Clean old install
rm -rf \
    "/opt/python-$MAJOR_VERSION/bin" \
    "/opt/python-$MAJOR_VERSION/include" \
    "/opt/python-$MAJOR_VERSION/lib" \
    "/opt/python-$MAJOR_VERSION/share"

# Install new files
make -j "$JOBS" install

# Strip binaries
strip "/opt/python-$MAJOR_VERSION/bin/python${MAJOR_VERSION}"
# Not present since 3.8: strip "/opt/python-$MAJOR_VERSION/bin/python${MAJOR_VERSION}m"
find "/opt/python-$MAJOR_VERSION/lib" -name '*.a' -print0 | xargs -0 strip
find "/opt/python-$MAJOR_VERSION/lib" -name '*.so' -print0 | xargs -0 strip

# Remove the untarred source
cd "/opt/python-$MAJOR_VERSION/src"
rm -rf "${TMPDIR}/Python-$VERSION"

# Remove temp build directory
rmdir "${TMPDIR}"

# Success
cat "/opt/python-$MAJOR_VERSION/src/build-success.txt"
