#!/bin/bash
# QT-CI Project
# License: Apache-2.0
# https://github.com/benlau/qtci

function usage() {
    echo "Usage:"
    echo "extract-qt-installer qt-installer output_path"
    echo "extract-qt-installer --list-packages qt-installer"
    exit -1
}

LIST_PACKAGES=0

getopt --test > /dev/null 2>&1
GETOPT_RET_CODE=$?

set -e #quit on error

if [ "$GETOPT_RET_CODE" != "4" ]
then
    echo "Warning: gnu-getopt is not installed. Long parameter like '--list-package' will not be working. Please install gnu-getopt by 'brew install gnu-getopt'"   
else

	OPTS=`getopt -o l --long list-packages --long disable-progress-report -n "extract-qt-installer" -- "$@"`

    eval set -- "$OPTS"

    while true
    do
      case "$1" in
        --list-packages)
          LIST_PACKAGES=1
          shift;;
	    --disable-progress-report)
	      DISABLE_PROGRESS_REPORT=1
	      shift;;
        --) shift;break;;
        *) shift;;
      esac
    done
fi


export PATH=$PATH:$PWD
export WORKDIR=$PWD
INSTALLER=$1
OUTPUT=$2
SCRIPT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/qt-install.qs
PACKAGES=$QT_CI_PACKAGES

if [ $LIST_PACKAGES -gt 0 ]
then 

	if [ $# -lt 1 ]
	then
		usage
	fi
	
	OUTPUT="/tmp/Qt"

else

	if [ $# -lt 2 ]
	then
		usage
	fi

	if [[ ! "${OUTPUT:0:1}" = "/" ]] 
	then 
		echo output path must be an absolute path
		exit -1
	fi
    
fi


chmod u+x $1
if [ -n "$QT_CI_DEBUG" ] 
then
	$INSTALLER -v --script $SCRIPT QTCI_LIST_PACKAGES="$LIST_PACKAGES" QTCI_PACKAGES="$PACKAGES" QTCI_OUTPUT="$OUTPUT" | grep "\(QTCI\|operation\)"
	exit 0
fi

unset DISPLAY

# platform minimal doesn't work on macos 10.14, 10.15.  It did work on 10.13.
# https://bugreports.qt.io/browse/QTIFW-1471
PLATFORM="--platform minimal"
if [ "$(uname)" = "Darwin" ]; then
  vn=$(sw_vers -productVersion | cut -d. -f2,2)
  if [ $vn -ge 14 ]; then
     unset PLATFORM
  fi
fi

if [ -n "$DISABLE_PROGRESS_REPORT" ]
then
	$INSTALLER $PLATFORM --script $SCRIPT QTCI_LIST_PACKAGES="$LIST_PACKAGES" QTCI_PACKAGES="$PACKAGES" QTCI_OUTPUT="$OUTPUT" 
else
	if [ -n "$VERBOSE" ]
	then
		$INSTALLER --verbose $PLATFORM --script $SCRIPT QTCI_LIST_PACKAGES="$LIST_PACKAGES" QTCI_PACKAGES="$PACKAGES" QTCI_OUTPUT="$OUTPUT"
	else
		$INSTALLER --verbose $PLATFORM --script $SCRIPT QTCI_LIST_PACKAGES="$LIST_PACKAGES" QTCI_PACKAGES="$PACKAGES" QTCI_OUTPUT="$OUTPUT" | grep "\(QTCI\|operation\)"
	fi
fi


