#!/usr/bin/env bash
# Downloads the "Windows 7 Theme" GTK theme + icon pack from
# https://scripts.gabesville.com/Gabesville/Debian-Linux (Ricing/Windows-7-Theme)
# and installs them into the correct dot-folders under $HOME
# Usage:
#   chmod +x install-win7-theme.sh
#   ./install-win7-theme.sh

set -euo pipefail

BASE_URL="https://scripts.gabesville.com/Gabesville/Debian-Linux/raw/branch/main/Ricing/Windows-7-Theme"

# filename -> destination dot-folder
declare -A PACKAGES=(
  ["Windows-7-theme.zip"]="$HOME/.themes"
  ["Windows-7-icons.zip"]="$HOME/.icons"
)

WORKDIR="$(mktemp -d)"
trap 'rm -rf "$WORKDIR"' EXIT

command -v unzip >/dev/null 2>&1 || { echo "unzip is required. Install it with: sudo apt install unzip" >&2; exit 1; }
command -v curl  >/dev/null 2>&1 || { echo "curl is required. Install it with: sudo apt install curl" >&2; exit 1; }

for zipname in "${!PACKAGES[@]}"; do
  dest="${PACKAGES[$zipname]}"
  url="${BASE_URL}/${zipname}"
  extract_dir="${WORKDIR}/${zipname%.zip}"

  echo "==> Downloading ${zipname}..."
  curl -fL --progress-bar -o "${WORKDIR}/${zipname}" "$url"

  echo "==> Extracting ${zipname}..."
  mkdir -p "$extract_dir"
  unzip -q "${WORKDIR}/${zipname}" -d "$extract_dir"

  mkdir -p "$dest"

  # Figure out whether the zip already contains a single top-level folder
  # (e.g. "Windows 7/") or a bunch of loose files/folders at the root.
  # If it's a single folder, move that folder's *contents* straight into
  # the dot-folder so we don't end up with an unnecessary nested dir.
  mapfile -t top_level < <(find "$extract_dir" -mindepth 1 -maxdepth 1)

  if [[ ${#top_level[@]} -eq 1 && -d "${top_level[0]}" ]]; then
    src="${top_level[0]}"
  else
    src="$extract_dir"
  fi

  echo "==> Installing into ${dest}..."
  for item in "$src"/*; do
    name="$(basename "$item")"
    target="${dest}/${name}"
    if [[ -e "$target" ]]; then
      echo "    - ${name} already exists in ${dest}, replacing..."
      rm -rf "$target"
    fi
    mv "$item" "$target"
  done

  echo "==> ${zipname} installed to ${dest}"
  echo
done

echo "Done"