#!/usr/bin/env bash
set -xe
[ ! -f /build/.gitignore ] && {
    echo "The appimage folder is not mounted in the docker"
    exit 1
}
[ ! -d squashfs-root ] && {
    echo "The appimage utilities where not deployed..."
    exit 1
}

export ARCH=$(arch)
export PATH="$PWD/squashfs-root/usr/bin:$PATH"
export LD_LIBRARY_PATH="$PWD/squashfs-root/usr/lib:$LD_LIBRARY_PATH"
export QMAKE=/usr/lib/qt6/bin/qmake6

function join_by() {
    local d=${1-} f=${2-}
    if shift 2; then
        printf %s "$f" "${@/#/$d}"
    fi
}

function deploy() {
    local EXEC=${1,,}
    local WITHQTPLUGIN="$2"

    local  EXTRA_PLATFORM_PLUGINS="libqxcb.so;libqwayland-egl.so;libqwayland-generic.so;"
    export EXTRA_PLATFORM_PLUGINS

    local EXCLUDE_LIBS="libgdk_pixbuf libpango libcairo libgio libglib libgmodule libgobject libgthread libX11-xcb libxcb-"
    local EXCLUDE_LIBS="-name *$(join_by "* -or -name *" $EXCLUDE_LIBS)*"

    local qtPlugin=()
    if [[ "x$WITHQTPLUGIN" == "x1" ]]; then
        qtPlugin+=(--plugin qt)
    fi

    # Will do most of the work
    linuxdeploy -v1 --appdir ${EXEC^} -e target/release/${EXEC} \
        -i ${EXEC}/${EXEC}.png -d ${EXEC}/${EXEC}.desktop "${qtPlugin[@]}"

    # Handle aftermath things here, we force copy the qt plugins for wayland and remove unwanted
    # libs... NOTE: For now we force the xcb platform because of troubles with wayland...
    mkdir -p ${EXEC^}/apprun-hooks/
    find ${EXEC^}/usr/lib/ -type f -and \( ${EXCLUDE_LIBS} \) -delete
    cp LICENSE CHANGELOG.md CONTRIBUTING.md ${EXEC^}/
    install -Dm644 ${EXEC}/${EXEC}.appdata.xml ${EXEC^}/usr/share/metainfo/${EXEC}.appdata.xml
    case ${*:2} in
        *qt*)
            cp -rf /usr/lib/x86_64-linux-gnu/qt6/plugins/wayland-shell-integration ${EXEC^}/usr/plugins/wayland-shell-integration
            for SHELL in ${EXEC^}/usr/plugins/wayland-shell-integration/*; do
                patchelf --force-rpath --set-rpath \$ORIGIN/../../lib:\$ORIGIN ${SHELL}
            done
            ;;
        *);;
    esac

    # Custom AppRun script!
    unlink ${EXEC^}/AppRun \
        && touch ${EXEC^}/AppRun \
        && chmod +x ${EXEC^}/AppRun
cat > ${EXEC^}/AppRun <<EOF
#!/usr/bin/env bash
set -e
this_dir="\$(readlink -f "\$(dirname "\$0")")"
[ ! -n "\$(find "\$this_dir"/apprun-hooks/ -maxdepth 0 -type d -empty 2>/dev/null)" ] \
    && [ -d "\$this_dir"/apprun-hooks/ ] \
    && {
        for HOOK in "\$this_dir"/apprun-hooks/*; do
            source "\$HOOK"
        done
}
exec "\$this_dir/usr/bin/${EXEC}" \$@
EOF

    # Pack the AppImage
    appimagetool -v --comp xz ${EXEC^}
    mv ${EXEC^}-$(arch).AppImage /build/
}

deploy lkt
deploy amadeus
deploy lektord 1