#!/usr/bin/env bash

scriptDir="$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")"
appletDir="${scriptDir%/contents/*}"
configDir="${APDATIFIER_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/apdatifier}"
cacheDir="${APDATIFIER_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/apdatifier}"
localDir="${XDG_LOCAL_HOME:-$HOME/.local/share}"
iconsDir="$localDir/icons/breeze/status/22"
notifDir="$localDir/knotifications6"
config="$configDir/config.conf"
notif="apdatifier.notifyrc"
icons=(apdatifier-plasmoid.svg
       apdatifier-packages.svg
       apdatifier-package.svg
       apdatifier-flatpak.svg)

test -d "$configDir" || mkdir -p "$configDir"
test -f "$config" || touch "$config"

test -d "$cacheDir" || mkdir -p "$cacheDir"
# Migrate cache files from old location
[[ -f "$configDir/updates.json" && ! -f "$cacheDir/updates.json" ]] && mv "$configDir/updates.json" "$cacheDir/updates.json"
[[ -f "$configDir/news.json" && ! -f "$cacheDir/news.json" ]] && mv "$configDir/news.json" "$cacheDir/news.json"

for dir in $iconsDir $notifDir; do
    test -d "$dir" || mkdir -p "$dir"
done

for icon in "${icons[@]}"; do
    test -f "$iconsDir/$icon" || cp "$appletDir/contents/ui/assets/icons/$icon" "$iconsDir"
done

test -d "$notifDir" && cat > "$notifDir/$notif" << EOF
[Global]
IconName=apdatifier-plasmoid
Comment=Apdatifier

[Event/updates]
Name=New updates
Comment=Event when updates notification enabled without sound
Action=Popup

[Event/updatesSound]
Name=New updates (with sound)
Comment=Event when updates notification enabled with sound
Action=Popup|Sound
Sound=service-login

[Event/error]
Name=Error
Comment=Event when error notification enabled without sound
Action=Popup

[Event/errorSound]
Name=Error (with sound)
Comment=Event when errors notification enabled with sound
Action=Popup|Sound
Sound=dialog-error-serious

[Event/news]
Name=News
Comment=Event when news notification without sound
Action=Popup

[Event/newsSound]
Name=News (with sound)
Comment=Event when news notification with sound
Action=Popup|Sound
Sound=dialog-information
EOF
