#!/bin/bash
#
# Macroscop: Flatpak Offline Install

readonly RUNTIME_BRANCH="23.08"
readonly TARGET_DIR="$HOME/flatpak_macroscop"

if [ -z "$1" ]; then
  APP_BRANCH="latest"
else
  APP_BRANCH="$1"
fi

declare -A osInfo;
osInfo[/etc/altlinux-release]=apt-get
osInfo[/etc/redhat-release]=yum
osInfo[/etc/arch-release]=pacman
osInfo[/etc/gentoo-release]=emerge
osInfo[/etc/SuSE-release]=zypp
osInfo[/etc/debian_version]=apt-get
osInfo[/etc/alpine-release]=apk

for os in "${!osInfo[@]}"
do
  if [[ -f $os ]];then
    sudo "${osInfo[$os]}" install -y flatpak
  fi
done

sudo flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
sudo flatpak remote-add --if-not-exists macroscop https://packages.macroscop.com/flatpak/macroscop.flatpakrepo

sudo flatpak -y install --noninteractive flathub org.freedesktop.Platform//${RUNTIME_BRANCH}
sudo flatpak -y install --noninteractive flathub org.freedesktop.Platform.Compat.i386//${RUNTIME_BRANCH}
sudo flatpak -y install --noninteractive flathub org.freedesktop.Platform.GL.default//${RUNTIME_BRANCH}
sudo flatpak -y install --noninteractive flathub org.freedesktop.Platform.GL32.default//${RUNTIME_BRANCH}

sudo flatpak -y install --noninteractive macroscop com.macroscop.client//"${APP_BRANCH}"

mkdir -p "${TARGET_DIR}"

echo "Please, wait..."

flatpak build-bundle /var/lib/flatpak/repo "${TARGET_DIR}"/macroscop_"${APP_BRANCH}".flatpak com.macroscop.client "${APP_BRANCH}"
flatpak build-bundle /var/lib/flatpak/repo "${TARGET_DIR}"/org.freedesktop.Platform_${RUNTIME_BRANCH}.flatpak org.freedesktop.Platform ${RUNTIME_BRANCH} --runtime
flatpak build-bundle /var/lib/flatpak/repo "${TARGET_DIR}"/org.freedesktop.Platform.Compat.i386_${RUNTIME_BRANCH}.flatpak org.freedesktop.Platform.Compat.i386 ${RUNTIME_BRANCH} --runtime
flatpak build-bundle /var/lib/flatpak/repo "${TARGET_DIR}"/org.freedesktop.Platform.GL.default_${RUNTIME_BRANCH}.flatpak org.freedesktop.Platform.GL.default ${RUNTIME_BRANCH} --runtime
flatpak build-bundle /var/lib/flatpak/repo "${TARGET_DIR}"/org.freedesktop.Platform.GL32.default_${RUNTIME_BRANCH}.flatpak org.freedesktop.Platform.GL32.default ${RUNTIME_BRANCH} --runtime

cat > "${TARGET_DIR}"/install.sh <<EOF
#!/bin/bash
#
# Macroscop: Flatpak Offline Install

flatpak --user -y install --noninteractive org.freedesktop.Platform_${RUNTIME_BRANCH}.flatpak
flatpak --user -y install --noninteractive org.freedesktop.Platform.Compat.i386_${RUNTIME_BRANCH}.flatpak
flatpak --user -y install --noninteractive org.freedesktop.Platform.GL.default_${RUNTIME_BRANCH}.flatpak
flatpak --user -y install --noninteractive org.freedesktop.Platform.GL32.default_${RUNTIME_BRANCH}.flatpak
flatpak --user -y install --noninteractive macroscop_${APP_BRANCH}.flatpak
EOF

chmod +x "${TARGET_DIR}"/install.sh
