
set -e
#set -x

#################################
# Identify OS and Architecture  #
#################################

# OS in "lin", "win", "unknow"
# ARCH in "x86", "x86_64"
OS=""
ARCH=""

initOS() {
    UNAME=$(uname -a)
    if echo "$UNAME" | grep -i "win" >/dev/null; then
            OS="win"
    else
            if echo "$UNAME" | grep -i "lin" >/dev/null ; then
                    OS="lin"
            else
                    OS="unknown"
            fi
    fi
    if echo "$UNAME" | egrep -i "(x86_64)|(amd64)" >/dev/null ; then
            ARCH="x86_64"
    else
            ARCH="x86"
    fi
}

##################################################
# Fix albsolute symbolic links in native folder  #
##################################################
fixsymlinks() {
    if [ "$OS" != "lin" ] ; then
        return
    fi
    cd "$GVSIG_INSTALL_FOLDER/native"
    
    #
    # GDAL libs
    ln -sf libgdal.so.1.15.1 libgdal.so 
    ln -sf libgdal.so.1.15.1 libgdal.so.1
    #
    # ECW libs
    ln -sf libNCSCnet.so.0 libNCSCnet.so 
    ln -sf libNCSEcwC.so.0 libNCSEcwC.so
    ln -sf libNCSEcw.so.0 libNCSEcw.so
    ln -sf libNCSUtil.so.0 libNCSUtil.so
    
    cd -
}

create_config_file() {
    echo -e "
    ###
    GVSIG_HOME_FOLDER=\"\$GVSIG_INSTALL_FOLDER/home/gvSIG\"
    GVSIG_JAVA_PARAMS=\"-DgvSIG.home=\\\"\$GVSIG_INSTALL_FOLDER/home\\\"\"
    ###
    " > "$GVSIG_INSTALL_FOLDER/gvSIG.config"
}

main() {

    if [ "$GVSIG_PORTABLE_TARGET_FOLDER" == "" ] ; then
      echo -e "Usage:\n  $0 target-folder"
      exit 1
    fi

    echo "Creating gvSIG.config"
    create_config_file
    
    echo "Fix symbolic links"
    fixsymlinks

    FOLDERNAME=$(basename "${GVSIG_INSTALL_FOLDER}")
    cd "${GVSIG_INSTALL_FOLDER}/.."

    echo "Removing target (${GVSIG_PORTABLE_TARGET_FOLDER}/${FOLDERNAME}.zip)"
    rm -f "${GVSIG_PORTABLE_TARGET_FOLDER}/${FOLDERNAME}.zip" 
    
    echo "Creatinng zip with the portable in ${GVSIG_PORTABLE_TARGET_FOLDER}/${FOLDERNAME}.zip"
    zip -r "${GVSIG_PORTABLE_TARGET_FOLDER}/${FOLDERNAME}.zip" "$FOLDERNAME"

}

######################################################
# Go into the gvSIG installation folder, just in case
cd "$(dirname $0)"
cd ..

# gvSIG installation folder
export GVSIG_INSTALL_FOLDER="$PWD"

export GVSIG_PORTABLE_TARGET_FOLDER="$1"

main
