#!/bin/bash
#
# Macroscop: Flatpak for ALT Linux
set -x
readonly SCRIPT_URL="https://packages.macroscop.com/flatpak/install/flatpak-offline-macroscop.sh"
readonly SCRIPT_FILE="flatpak-offline.sh"
readonly TARGET_DIR="$HOME/flatpak_depends"
readonly PACKAGE="flatpak"

declare -A downloaded_packages

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

mkdir "${TARGET_DIR}"

cd "${TARGET_DIR}" || exit

sudo apt-get clean && sudo apt-get update > /dev/null
download_package_and_dependencies() {
  local package=$1

  if [ "${downloaded_packages[$package]}" ]; then
    return
  fi

  sudo apt-get install --reinstall -d -y "$package"

  downloaded_packages[$package]=1

  dependencies=$(apt-cache depends "$package" | grep "Depends:" | sed "s/.*Depends: //" | tr -d '<>')
  for dependence in $dependencies; do
    download_package_and_dependencies "$dependence"
  done
}

download_package_and_dependencies "$PACKAGE"

sudo cp -R /var/cache/apt/archives/*.rpm "${TARGET_DIR}"
sudo chmod 777 "${TARGET_DIR}"


cd "$HOME" || exit

wget "$SCRIPT_URL" -O "$SCRIPT_FILE"
chmod +x "$SCRIPT_FILE"
bash "$SCRIPT_FILE" "$APP_BRANCH"
rm "$SCRIPT_FILE"

tar -czf flatpak.tgz -C "$HOME" flatpak_depends/* flatpak_macroscop/*

rm -rf flatpak_*
