#!/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

ARCH=$(arch)
if [ $ARCH == "i386" ] ; then
  export MACOSX_DEPLOYMENT_TARGET=10.9
else
  export MACOSX_DEPLOYMENT_TARGET=10.13
fi


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_libsqlite {
    cd /var/root
    tar -xvf  sqlite-autoconf-*.tar.gz
    cd sqlite-autoconf-*/
    ./configure --prefix=$PREFIX LDFLAGS="-Wl,-rpath,$PREFIX/lib/" PKG_CONFIG_PATH=$PREFIX/lib/pkgconfig --enable-shared CFLAGS="-DTCLSH=0"
    make
    make install
}


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/
	[ -f $PREFIX/bin/python3 ] || ln -s ./python3.10 $PREFIX/bin/python3
    [ -f $PREFIX/bin/python ] || ln -s ./python3.10 $PREFIX/bin/python
}

function cleanup {
    rm -f $PREFIX/bin/{gss-client,k5srvutil,kadmin,kdestroy,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_libsqlite
build_xz
build_libkrb5
build_python
cleanup

exit
