#!/bin/bash

# Configures MEGA SDK (creates config.h file)
root_dir=`pwd`
rm_archives=0
archives=$root_dir/archives

display_help() {
    local app=$(basename "$0")
    echo ""
    echo "Usage:"
    echo " $app [-e] [-f] [-g] [-q] [-z]"
    echo ""
    echo "Configure MEGA SDK (creates config.h file)"
    echo ""
    echo "Options:"
    echo " -e : Download and link CARES statically."
    echo " -f : Force software packages rebuild."
    echo " -g : Download and link CURL statically."
    echo " -i : Do not download and link LIBMEDIAINFO statically."
    echo " -q : Download and link CRYPTOPP statically."
    echo " -z : Do not download and link ZLIB statically."
    echo " -W : Download and link LIBRAW statically."
    echo ""
}

FLAG_CRYPTOPP=""
FLAG_CARES=""
FLAG_CURL=""
FLAG_DISABLE_ZLIB=""

while getopts ":efgiqzW" opt; do
    case $opt in
        q) 
            FLAG_CRYPTOPP="-q"; 
            ;;
        g) 
            FLAG_CURL="-g"; 
            ;;
        i)
            FLAG_LIBMEDIA="-i";
            ;;
        e) 
            FLAG_CARES="-e"; 
            ;;
        f)
            if [ -d "$archives" ]; then
                rm -fr $archives
            fi
            ;;
        h)
            display_help $0
            exit
            ;;
        z) 
            FLAG_DISABLE_ZLIB="-z"; 
            ;;
        W)
            FLAG_RAW="-W";
            ;;
        \?)
            display_help $0
            exit
            ;;
        *)
            display_help $0
            exit
            ;;
    esac
done
shift $((OPTIND-1))

# if archives are not yet downloaded
if [ ! -d "$archives" ]; then
    mkdir $archives
    ./MEGASync/mega/contrib/build_sdk.sh $FLAG_CRYPTOPP -n -N $FLAG_CARES $FLAG_LIBMEDIA $FLAG_CURL $FLAG_DISABLE_ZLIB $FLAG_RAW -w -s -v -u -o $archives
    rm_archives=1
fi

cd MEGASync/mega
./contrib/build_sdk.sh \
    $FLAG_CRYPTOPP \
    -o $archives \
    $FLAG_CARES $FLAG_CURL $FLAG_LIBMEDIA $FLAG_DISABLE_ZLIB $FLAG_RAW \
    -l \
    -n \
    -N \
    -c \
    -t \
    -s \
    -v \
    -I \
    -u \
    -p $root_dir/MEGASync/mega/bindings/qt/3rdparty

# For compatibility with other platforms
ln -sf $root_dir/MEGASync/mega/bindings/qt/3rdparty/lib $root_dir/MEGASync/mega/bindings/qt/3rdparty/libs

cd $root_dir

if [ $rm_archives -eq 1 ]; then
    if [ -d "$archives" ]; then
        rm -fr $archives
    fi
fi
