#!/bin/bash
set -e

PREFIX="$1"

if [ -z "$PREFIX"  ]; then
        PREFIX='/opt/python311/'
fi

if [ -n "$PREFIX"  ]; then
	PREFIX='/opt/python311/'
fi

export LANG=C
export MACOSX_DEPLOYMENT_TARGET=10.13

mkdir -p $PREFIX

function build_openssl {
    cd /var/root
    tar -zxvf openssl-*.tar.gz
    cd openssl-*/
    ./config --prefix=$PREFIX  -Wl,-rpath,$PREFIX/lib/ --libdir=$PREFIX/lib --openssldir=/etc/ssl/certs/
    make -j`sysctl -n hw.logicalcpu` 
    make install_sw  
}

function build_xz {
    cd /var/root
    tar -xvf xz-*.tar.gz
    cd xz-*/
    export PATH=$PREFIX/bin:$PATH
    ./configure --prefix=$PREFIX -C    LDFLAGS="-Wl,-rpath,$PREFIX/lib/" PKG_CONFIG_PATH=$PREFIX/lib/pkgconfig CFLAGS="-I $PREFIX/include"
    make -j`sysctl -n hw.logicalcpu` 
    make install 
}

function build_libkrb5 {
    cd /var/root
    tar -zxvf krb5-*.tar.gz
    cd krb5-*/src/
    ./configure  --prefix=$PREFIX LDFLAGS="-Wl,-rpath,$PREFIX/lib/" PKG_CONFIG_PATH=$PREFIX/lib/pkgconfig/ 
    make -j`sysctl -n hw.logicalcpu`  
    make install 
}

function build_python {
    cd /var/root
    tar -zxvf Python-*.tgz
    cd Python-*/
    ./configure --prefix=$PREFIX -C --with-openssl=$PREFIX/ --enable-shared LDFLAGS="-Wl,-rpath,$PREFIX/lib/" PKG_CONFIG_PATH=$PREFIX/lib/pkgconfig/
    make -j`sysctl -n hw.logicalcpu`  altinstall 
    rm -f $PREFIX/bin/{2to3*,idle3*} 
    rm -Rf $PREFIX/etc/
	ln -s $PREFIX/bin/python3.11 $PREFIX/bin/python3
    ln -s $PREFIX/bin/python3.11 $PREFIX/bin/python
}

function cleanup {
    rm -f $PREFIX/bin/{gss-client,k5srvutil,kadmin,kdestroy,kinit,klist,kpasswd,ksu,kswitch,ktutil,kvno,sclient,sim_client,uuclient}
    rm -Rf $PREFIX/{sbin,share,var}
    rm -Rf $PREFIX/lib/python3.*/test
}

build_openssl
build_xz
build_libkrb5
build_python
cleanup

exit
