#!/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/7za"
pythonArchive="$mydir/Tools/Python3.framework.7z"
FRAMEWORK_FOLDER="/Library/Application Support/Adobe/Reader/Frameworks"
ACRO_PYTHON3_FRAMEWORK="$FRAMEWORK_FOLDER/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 "$ACRO_PYTHON3_FRAMEWORK" ]
then
     echo "Deleting existing python framework at $ACRO_PYTHON3_FRAMEWORK"
     rm -rf "$ACRO_PYTHON3_FRAMEWORK"
fi

#Create frameworks folder if does not exists.
if [ ! -d "$FRAMEWORK_FOLDER" ]
then
     mkdir  "$FRAMEWORK_FOLDER"
     chmod 755 "$FRAMEWORK_FOLDER"
     echo "Creating folder at existing $FRAMEWORK_FOLDER"
fi


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

#create product framework folder if not existing
mkdir -p "$FRAMEWORK_FOLDER"

#extract python framework
if  extract_acro_python
then

    echo "extracting-- python framework  at : $FRAMEWORK_FOLDER"
    $exe7z x "$pythonArchive" -o"$FRAMEWORK_FOLDER" -y
    echo  "done extracting python framework"
    echo  "Will set permissions of python framework"
    chmod -R 755 "$ACRO_PYTHON3_FRAMEWORK"
    
fi
