#!/bin/bash

function exitWithErrorCode
{
    echo "ERROR: PreInstall exited with error code $1."
    exit $1
}

# SUCCESS is 0 - when machine OS version >= 12.3
function extract_acro_python()
{
    current_os_major_version=$(sw_vers -productVersion 2>&1 | sed 's/\([0-9]*\)\.\([0-9]*\).*/\1/')
    current_os_minor_version=$(sw_vers -productVersion 2>&1 | sed 's/\([0-9]*\)\.\([0-9]*\).*/\2/')
    required_major_version=12
    required_minor_version=3
   if [[
            ($current_os_major_version -gt $required_major_version) ||
            (($current_os_major_version -eq $required_major_version) && ($current_os_minor_version -ge $required_minor_version))
    ]]
    then
        echo "Mac OS version [$mac_os_version] is equal/higher than 12.3."

        if [[ -e "$PYTHON_MARKER_FILE" ]];
        then
            echo "Marker file found. Will not extract acro_python"
            return 1
        fi
    else
        echo "Mac OS version [$mac_os_version] is less than 12.3.  Will not extract acro_python"
        return 1
    fi

    return 0
}


mydir=`pwd`
exe7z="$mydir/Tools/7zz"
pythonArchive="$mydir/Tools/Python3.framework.7z"
ACRO_PYTHON3_FOLDER="$INSTALLER_TEMP/Python"
OLD_ACRO_PYTHON3_FRAMEWORK="/Library/Application Support/Adobe/Reader/Frameworks/Python3.framework"
PYTHON_MARKER_FILE="/Library/Application Support/Adobe/Reader/Frameworks/python_marker"
# Check if zip toolis present
if [ ! -e $exe7z ]
then
    echo "ERROR: Zip tool not found  within installer. Installation failure."
    exitWithErrorCode -1
fi

#Delete existing python framework of it exists
if [ -d "$OLD_ACRO_PYTHON3_FRAMEWORK" ]
then
     echo "Deleting existing python framework at $OLD_ACRO_PYTHON3_FRAMEWORK"
     rm -rf "$OLD_ACRO_PYTHON3_FRAMEWORK"
fi

if [ ! -e "$pythonArchive" ]
then
    echo "ERROR: Python archive not found in installer"
    exitWithErrorCode -1
fi


#extract python framework
if  extract_acro_python
then
    mkdir -m 700  "$ACRO_PYTHON3_FOLDER"   # This will also help against privilidge escalation attacks using symlink or hardlink as it will give error if already existing
    retval=$?
    if [ $retval -ne 0 ]
    then
        echo "ERROR while creating folder: $ACRO_PYTHON3_FOLDER"
        exitWithErrorCode -1
    fi
    echo "extracting-- python framework  at : $ACRO_PYTHON3_FOLDER"
    $exe7z x "$pythonArchive" -o"$ACRO_PYTHON3_FOLDER" -y -snld
    echo  "done extracting python framework"
    
fi
