#!/usr/bin/env bash

# Copyright 2021 Josh Holbrook
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

BACKGROUNDS=""

IFS=: read -r -d '' -a BACKGROUND_PATH < <(printf '%s:\0' "$(kbconfig get background path)")

for path in "${BACKGROUND_PATH[@]}"; do
  if [ -n "${BACKGROUNDS}" ]; then
    BACKGROUNDS="${BACKGROUNDS}
"
  fi
  BACKGROUNDS="${BACKGROUNDS}$(find "${path}" -iname '*.png' -o -iname '*.jpg')"
done

SELECTED="$(echo "${BACKGROUNDS}" | fzf --preview 'viu -b -w 60 {}')"

if [[ "${OSTYPE}" == "darwin"* ]]; then
  SANITIZED="$(echo "${SELECTED}" | sed 's/"/""/g')"

  osascript -e 'tell application "Finder"
    set desktop picture to POSIX file "'"${SANITIZED}"'"
    end tell'
else
  SWAY_ARGS="$(kbconfig get background sway_args)"

  swaymsg output '*' bg "${SELECTED}" ${SWAY_ARGS}

  echo "To make the background permanent, add this your sway config:

      output * bg ${SELECTED} ${SWAY_ARGS}"
fi

