#!/bin/bash

############################################################################
#                                                                          #
#  Copyright (c) 2001, 2025 NoMachine, http://www.nomachine.com/.          #
#                                                                          #
#  Simple configure script used to build as part of the NX system.         #
#                                                                          #
#  Redistribution and use of the present software is allowed according     #
#  to terms specified in the file LICENSE which comes in the source        #
#  distribution.                                                           #
#                                                                          #
#  Check http://www.nomachine.com/licensing.html for other options.        #
#                                                                          #
#  NX and NoMachine are trademarks of NoMachine S.a.r.l.                   #
#                                                                          #
#  All rights reserved.                                                    #
#                                                                          #
############################################################################

create_makefile_failed()
{
  echo -ne "configure: error: can't generate the original Makefile\n\n"

  rm -f config.status parallel.status install.status

  exit 1
}

set_flags ()
{
  flags="--enable-static --enable-shared --disable-gpl --disable-avs"

  if [ "$TARGET" = "Linux64"   ] || [ "$TARGET" = "Linux32"   ] ||
     [ "$TARGET" = "Solaris"   ] || [ "$TARGET" = "Android"   ] ||
     [ "$TARGET" = "FreeBSD32" ] || [ "$TARGET" = "FreeBSD64" ] ||
     [ "$TARGET" = "iOS"       ] || [ "$TARGET" = "MacOSX"    ];
  then
    flags="$flags --enable-pic" #-fPIC

    if [ "$TARGET" = "iOS" ] || [ "$TARGET" = "MacOSX" ];
    then
      flags="$flags --extra-asflags=-no-integrated-as"

      if test "$ARCHITECTURE" = "arm64";
      then

        #
        # FIXME: no optimization for ARM64 yet
        #

        flags="$flags --disable-asm"

      fi
    fi

    if [ "$CROSS" != "" ];
    then
      flags="$flags --cross-prefix=$CROSS-"
    fi
  elif [ "$TARGET" = "MinGW" ];
  then
    flags="$flags --host=i686-w64-mingw32"
  elif test "$TARGET" = "MinGW64";
  then
    flags="$flags --host=x86_64-w64-mingw32"
  fi

  flags="$flags --prefix=.libs"
}

#
# Include our configure functions.
#

if test -z "$ROOT"; then
  if test -x "../../../Configure"; then
    ROOT="../../.."
  else
    echo -ne "configure: error: can't find the main configure script\n\n"
    exit 1
  fi
fi

. $ROOT/Configure --functs || include_failed

#
# Setup the configuration environment.
#

setup_configure || setup_failed

#
# Check if the target is based on autoconf.
#

if test "$TARGET" = "Linux32"   || test "$TARGET" = "Linux64"   || \
   test "$TARGET" = "Cygwin"    || test "$TARGET" = "MinGW"     || \
   test "$TARGET" = "MacOSX"    || test "$TARGET" = "Solaris"   || \
   test "$TARGET" = "Android"   || test "$TARGET" = "iOS"       || \
   test "$TARGET" = "FreeBSD32" || test "$TARGET" = "FreeBSD64" || \
   test "$TARGET" = "MinGW64"; then

  #
  # Skip build for Android and iOS
  #

  if test "$TARGET" = "Android" || test "$TARGET" = "iOS"; then

    empty_makefile $ROOT || makefile_failed

    touch ./config.status

    exit 0

  fi

  #
  # Checking if --build argument is present.
  #   If not, use prebuilded libraries.
  #

  if ( [ $# -eq 1 ] && [ "$1" = "--build" ])                    || \
     [ "$TARGET" = "FreeBSD32" ] || [ "$TARGET" = "FreeBSD64" ] || \
     [ "$TARGET" = "Solaris"   ]
  then

    LDFLAGS="$LDFLAGS -L$BUILD/lib"

    export LDFLAGS

    #
    # Generate a new Makefile.
    #
  
    echo -ne "configure: generating the original Makefile... "  
  
    cp -p Makefile.in Makefile || create_makefile_failed

    echo -ne "Makefile\n"

    #
    # Generate a new configure script.
    #

    echo -ne "configure: generating the original configure script... "

    cp -p configure.in reconfig.status || create_failed

    echo -ne "reconfig.status\n"

    #
    # Run the script with our parameters.
    #

    echo -ne "configure: running the original configure script... "

    echo -ne "reconfig.status\n"

    set_flags

    #
    # Avoid linking problems on 64 bits.
    #

    if test "$TARGET" = "MacOSX"; then

      if test "$(get_xcode_version major)" -ge 5; then

        #
        # Unsupported option in new clang. Please remove
        # after component upgrade - new version already
        # has fix for it.
        #

        replace_string reconfig.status "-falign-loops=16" ""

        chmod 755 reconfig.status

      fi
    fi

    #
    # Select the correct grep command on
    # Solaris.
    #

    if test "$TARGET" = "Solaris"; then

      if test -f /usr/xpg4/bin/grep; then

        #
        # Our binary path must be prefixed to
        # other paths in order to use our sed
        # version.
        #

        PATH="$BUILD/bin:/usr/xpg4/bin:$PATH"

        export PATH

      fi

    fi

    run_configure $flags --prefix=.libs || run_failed

    #
    # Now post-process the generated makefile.
    #

    LDM32="-m32"
    LDM64="-m64"

    case "$ARCHITECTURE" in
      arm*|mips*|ppc*|power*)
        LDM32=
        LDM64=
        ;;
    esac

    LLDFLAGS="-lm"
    SOFLAGS=""
    case $TARGET in
      "Linux32")
        LLDFLAGS="$LLDFLAGS $LDM32"
        ;;
      "Linux64")
        LLDFLAGS="$LLDFLAGS $LDM64"
        SOFLAGS="-Xlinker -Bsymbolic"
        ;;
      "FreeBSD32")
        LLDFLAGS="$LLDFLAGS $LDM32"
        ;;
      "FreeBSD64")
        LLDFLAGS="$LLDFLAGS $LDM64"
        SOFLAGS="-Xlinker -Bsymbolic"
        ;;
      "MacOSX")
        LLDFLAGS="$LLDFLAGS -m64 -arch ${ARCHITECTURE}"
        # orginal x264 makefile adds -Wl,-read_only_relocs,suppress on macosx
        # but on 64bit architectures (target for nx) there is a warning
        # ld: warning: -read_only_relocs cannot be used with x86_64
        #
        # nx output doesn't write -shared option, x264 scripts writes it
        SOFLAGS="-Xlinker -single_module"
        ;;
      "MinGW")
        LLDFLAGS="$LLDFLAGS $LDM32"
        SOFLAGS="-Xlinker --enable-auto-image-base -Xlinker --large-address-aware"
        ;;
      "MinGW64")
        LLDFLAGS="$LLDFLAGS $LDM64"
        SOFLAGS="-Xlinker --enable-auto-image-base"
        ;;
    esac      

    if ! test "$TARGET" = "MinGW" && ! test "$TARGET" = "MinGW64" && \
       ! test "$TARGET" = "Android" ; then

      LLDFLAGS="$LLDFLAGS -lpthread"

    fi

    # there is a need to pass linker options also
    # the simplest way is to use LIBRARYLINK variable
    LIBRARYLINK="$LLDFLAGS $SOFLAGS"

    #
    # iOS uses static library
    #
    if test "$TARGET" = "iOS"; then

      add_archive config.mak "x264" "./.libs/lib" "128" "0" ""

    else

      add_library config.mak "x264" "./.libs/lib" "128" "0" "$LIBRARYLINK"

    fi

    #replace_string config.mak "libx264.a" "libx264.a"

    replace_environment config.mak

    replace_target config.mak all "original-all additional-all"

    replace_target config.mak install "all original-install additional-install"

    add_command config.mak install "cp -p .libs/include/x264.h $BUILD/include/"

    add_command config.mak install "cp -p .libs/include/x264_config.h $BUILD/include/"

    add_command config.mak distclean "rm -fr .libs"

    replace_string config.mak "^STRIP=" "#STRIP="

    add_dependency config.mak install "message"

    flush_targets config.mak

    replace_target Makefile clean "original-clean additional-clean"

    replace_target Makefile distclean "clean original-distclean additional-distclean"

    echo -ne "configure: creating ./config.status\n"

    made ./config.status

  elif [ "$TARGET" = "Linux32" ] || [ "$TARGET" = "Linux64" ] || \
       [ "$TARGET" = "MacOSX"  ] || [ "$TARGET" = "MinGW"   ] || \
       [ "$TARGET" = "Cygwin"  ] || [ "$TARGET" = "MinGW64" ]
  then
    create_makefile || makefile_failed

    replace_targets Makefile

    #
    # Setting missing flags.
    #

    set_flags

    build_dir=$(cd ../../../Build/ && pwd)
    prefix_flag="--prefix=$build_dir"

    source ./configure.in $prefix_flag $flags "--disable-asm"; set_x264_header

    add_command Makefile install "rm -rf ${ROOT}/Build/lib/libx264.*"

    #
    # Check if it is Linux ARM environment and choose proper prebuilt library.
    #

    if [ "${TARGET}" = "Linux32" ] && [ "${ARCHITECTURE}" = "armv6lhf" ]
    then
      add_command Makefile install "cp ./prebuilt/${TARGET}/armv6/libx264.* ${ROOT}/Build/lib/"

    elif [ "${TARGET}" = "Linux32" ] && [ "${ARCHITECTURE}" = "armv7lhf" ]
    then
      add_command Makefile install "cp ./prebuilt/${TARGET}/armv7/libx264.* ${ROOT}/Build/lib/"

    elif [ "${TARGET}" = "Linux64" ] && [ "${ARCHITECTURE}" = "arm64" ]
    then
      add_command Makefile install "cp ./prebuilt/${TARGET}/arm64/libx264.* ${ROOT}/Build/lib/"
    elif [ "${TARGET}" = "MacOSX" ] && [ "${ARCHITECTURE}" = "arm64" ]
    then
      add_command Makefile install "cp ./prebuilt/${TARGET}/arm64/libx264.* ${ROOT}/Build/lib/"
    else
      add_command Makefile install "cp ./prebuilt/${TARGET}/libx264.* ${ROOT}/Build/lib/"
    fi

    add_command Makefile install "cp ./x264.h ${ROOT}/Build/include/"
    add_command Makefile install "cp ./x264_142.h ${ROOT}/Build/include/"
    add_command Makefile install "cp ./x264_161.h ${ROOT}/Build/include/"
    add_command Makefile install "cp ./x264_config.h ${ROOT}/Build/include/"

    add_command Makefile distclean "rm -rf ${ROOT}/Build/lib/libx264.* ${ROOT}/Build/include/x264.h \
                                      ${ROOT}/Build/include/x264_142.h ${ROOT}/Build/include/x264_161.h \
                                      ${ROOT}/Build/include/x264_config.h ./config.log ./config.status \
                                      ./config.cache ./config.mak ./x264_config.h ./x264.pc ./config.h \
                                      ./install.status"

    flush_targets Makefile

    echo "configure: Using pre-built binary."

    made ./config.status
    
  fi
  
else

  echo -ne "configure: error: don't know what to do for target $TARGET\n\n"

  exit 1

fi
