#!/usr/bin/env bash
#
# SPDX-License-Identifier: LGPL-3.0-or-later
#
# Copyright (C) 2025 Perry Werneck <perry.werneck@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

# References:
#
#   https://stackoverflow.com/questions/1596945/building-osx-app-bundle
#   http://hints.macworld.com/article.php?story=20020311215452999
#   https://stackoverflow.com/questions/8680132/creating-nice-dmg-installer-for-mac-os-x
#   
# Tools:
#   https://github.com/create-dmg/create-dmg
#
APPNAME="pw3270"

APPDIR=${PWD}/${APPNAME}.app

rm -fr ${APPDIR}
mkdir -p ${APPDIR}
mkdir -p ${APPDIR}/Contents
mkdir -p ${APPDIR}/Contents/MacOS
mkdir -p ${APPDIR}/Contents/MacOS/lib
mkdir -p ${APPDIR}/Contents/Resources
mkdir -p ${APPDIR}/Contents/Resources/plugins

install_libraries() {

    # Copy the required libraries
    for path in $(otool -L ${1} | tail -n +2 | grep -v "/usr/lib/" | grep -v "/System" | cut -d\( -f1)
    do
        dpath="${APPDIR}/Contents/MacOS/lib/$(basename ${path})"

        if [ ! -e ${dpath} ]; then

            echo "Copying ${path} to ${dpath}"

            mkdir -p $(dirname ${dpath})

            if [ ! -e ${path} ]; then
                echo "Library ${path} not found, exiting"
                exit -1
            
            fi
            
            cp -v "${path}" "${dpath}"
            if [ "$?" != "0" ]; then
                echo "Error copying ${path}"
                exit -1
            fi
 
        fi

        install_name_tool \
            -change \
                ${path} \
                @executable_path/lib/$(basename ${path}) \
                ${1}
    done

    # Resolve library dependencies
    again=1
    while [ "${again}" == "1" ]
    do
        again=0
        for libname in $(find ${APPDIR}/Contents/MacOS/lib -name "*.dylib") $(find ${APPDIR}/Contents/MacOS/lib -name "*.so")
        do
            echo "Checking ${libname}"
            for path in $(otool -L ${libname} | tail -n +2 | grep -v "@executable_path/" | grep -v "/System/" | grep -v "/usr/lib/" | cut -d\( -f1)
            do
                dpath="${APPDIR}/Contents/MacOS/lib/$(basename ${path})"

                if [ ! -e "${dpath}" ]; then
                    again=1
                    cp -v "${path}" "${dpath}"
                    if [ "$?" != "0" ]; then
                        echo "Error copying ${path}"
                        exit -1
                    fi
                fi

                install_name_tool \
                    -change \
                        ${path} \
                        @executable_path/lib/$(basename ${path}) \
                        ${libname}

            done

        done

    done

}

install_schemas() {             

    SCHEMASDIR="${APPDIR}/Contents/Resources/glib-2.0/schemas"
    mkdir -p "${SCHEMASDIR}"

    gtk_schemas="org.gtk.Settings.FileChooser.gschema.xml"
    glib_schemas="gschema.dtd"

    for schema in ${gtk_schemas}
    do
        filepath=$(pkg-config --variable=prefix gtk+-3.0)/share/glib-2.0/schemas/${schema}
        echo ${filepath}
        cp -v \
            ${filepath} \
            "${SCHEMASDIR}"
        if [ "$?" != "0" ]; then
            exit -1
        fi
    done

    for schema in ${glib_schemas}
    do
        filepath=$(pkg-config --variable=prefix glib-2.0)/share/glib-2.0/schemas/${schema}
        echo ${filepath}
        cp -v \
            ${filepath} \
            "${SCHEMASDIR}"
        if [ "$?" != "0" ]; then
            exit -1
        fi
    done

    glib-compile-schemas --targetdir="${SCHEMASDIR}" "${SCHEMASDIR}"
    if [ "$?" != "0" ]; then
        exit -1
    fi

}

install_locale() {
    base_libraries="glib-2.0 gtk+-3.0"
    for library in ${base_libraries}
    do
        cp -R -v \
            $(pkg-config --variable=prefix ${library})/share/locale/* \
            ${APPDIR}/Contents/Resources/locale
        if [ "$?" != "0" ]; then
            echo "Error copying locale for ${library}"
            exit -1
        fi
    done
}

build_package() {

    # Reconfigure & build
    rm -fr .build
    meson setup \
        --prefix=/ \
        --buildtype=release \
        --reconfigure \
        --wipe \
        .build
    if [ "$?" != "0" ]; then
        echo "Meson setup has failed"
        exit -1
    fi

    meson compile -C .build
    if [ "$?" != "0" ]; then
        echo "Meson compile has failed"
        exit -1
    fi

    DESTDIR=${APPDIR}/Contents/MacOS meson install -C .build
    if [ "$?" != "0" ]; then
        echo "Meson compile has failed"
        exit -1
    fi

    mv ${APPDIR}/Contents/MacOS/bin/* ${APPDIR}/Contents/MacOS
    if [ "$?" != "0" ]; then
        echo "Error moving bin/* to ${APPDIR}/Contents/MacOS"
        exit -1
    fi

    mv ${APPDIR}/Contents/MacOS/share/* ${APPDIR}/Contents/Resources
    if [ "$?" != "0" ]; then
        echo "Error moving shared folders to ${APPDIR}/Contents/Resources"
        exit -1
    fi

    mv ${APPDIR}/Contents/Resources/${APPNAME}/*.xml ${APPDIR}/Contents/Resources
    if [ "$?" != "0" ]; then
        echo "Error moving xml files to ${APPDIR}/Contents/Resources"
        exit -1
    fi

    rmdir ${APPDIR}/Contents/MacOS/bin ${APPDIR}/Contents/MacOS/share ${APPDIR}/Contents/Resources/plugins
    if [ "$?" != "0" ]; then
        echo "Error remmoving unused paths"
        exit -1
    fi

}

install_loaders() {

    gdk-pixbuf-query-loaders | sed -e "s@$(brew --cellar)@./lib@g" > ${APPDIR}/Contents/Resources/gdk-pixbuf.loaders

    for from in $(gdk-pixbuf-query-loaders | grep $(brew --cellar) | grep -v "^#" | cut -d\" -f2)
    do
        to=$(echo ${from} | sed -e "s@$(brew --cellar)@${APPDIR}/Contents/MacOS/lib@g")
        mkdir -p $(dirname ${to})
        cp -v "${from}" "${to}"
        if [ "$?" != "0" ]; then
            echo "Error installing ${to}"
            exit -1
        fi
            
    done

}

install_icon() {
    echo ${1}
 
    mkdir -p "${APPDIR}/Contents/Resources/icons"

    icon_sizes=("16" "32" "64" "128" "256" "512" "1024")
    iconname=$(basename ${1} | cut -d. -f1)
    iconset="./iconsets/${iconname}.iconset"

    for ((i=1; i < ${#icon_sizes[*]}; i++))
    do
        mkdir -p ${iconset}

        size=${icon_sizes[$((i - 1))]}
        #magick -density "${size}" -background transparent "${1}" -resize ${size} "${iconset}/icon_${size}x${size}.png"
        rsvg-convert ${1} --width ${size} --format png --output "${iconset}/icon_${size}x${size}.png"

        if [ "$?" != "0" ]; then
            echo "Error converting ${1} to ${size}x${size}"
            exit -1
        fi
    done
    iconutil -c icns -o "${2}" "${iconset}"
    if [ "$?" != "0" ]; then
        echo "Error converting ${1} to icns"
        exit -1
    fi

    rm -fr ${iconset}

}

install_icons() {

    for icon in icons/*.svg
    do
        install_icon ${icon} "${APPDIR}/Contents/Resources/icons/$(basename ${icon} .svg).icns"
    done

    install_icon "./branding/${APPNAME}.svg" "${APPDIR}/Contents/Resources/${APPNAME}.icns"
    install_icon "./branding/${APPNAME}-symbolic.svg" "${APPDIR}/Contents/Resources/icons/${APPNAME}-symbolic.icns"

}

make_dmg() {

    # https://github.com/create-dmg/create-dmg

    rm -f *.dmg
    
    rsvg-convert mac/installer_background.svg --format png --output "installer_background.png"
    if [ ! "$?" == "0" ]; then
        exit -1
    fi

    create-dmg \
        --volname "${APPNAME}" \
        --eula LICENSE \
        --volicon "${APPDIR}/Contents/Resources/${APPNAME}.icns" \
        --window-pos 200 120 \
        --window-size 800 400 \
        --icon-size 100 \
        --icon "${APPNAME}.app" 200 190 \
        --hide-extension "${APPNAME}.app" \
        --background installer_background.png \
        --app-drop-link 600 185 \
        "${APPNAME}-$(grep "^#define PACKAGE_VERSION " .build/config.h | head -n 1 | cut -d\" -f2)-unstable.dmg" \
        "${APPDIR}"

}

#until [ -z "$1" ]
#do
#    if [ ${1:0:2} = '--' ]; then
#        tmp=${1:2}
#        parameter=${tmp%%=*}
#        parameter=$(echo $parameter | tr "[:lower:]" "[:upper:]")
#        value=${tmp##*=}
#
#        case "$parameter" in
#        *)
#            echo "Unexpect argument"
#            exit -1        
#        esac
#    fi
#
#    shift
#
#done

build_package
install_loaders ${APPDIR}/Contents/MacOS/lib
install_libraries ${APPDIR}/Contents/MacOS/${APPNAME}
install_locale
install_schemas
install_icons

# copy info.plist
cp -v mac/info.plist ${APPDIR}/Contents
if [ "$?" != "0" ]; then
    echo "Error copying info.plist"
    exit -1
fi

make_dmg


#echo "Build of ${INSTALL_IMAGE} is complete"
