#!/bin/sh -euf

. install2-init-functions

DEF_LINK_NAME="default_SL10"
RES= X= Y= SIZE= f= b= bg_res=
BG_NAME= NEW_DEFAULT=

# Get current Xorg resolution
RES="$(xrandr -q -d :0 | head -1 | sed -r -n 's/^.+[[:blank:]]+current[[:blank:]]+([[:digit:]]+)[[:blank:]]+x[[:blank:]]+([[:digit:]]+),.*$/\1x\2/p')"
X="${RES%x*}"
Y="${RES#*x}"

if [ -z "$X" ] || [ -z "$Y" ]; then
	exit 0
fi

case "$(($X*10/$Y))" in
	13) SIZE='4x3' ;;
	16) SIZE='16x10' ;;
	17) SIZE='16x9' ;;
esac
[ -n "$SIZE" ] || exit 0

# Change desktop background
BG_NAME="$(readlink $destdir/usr/share/backgrounds/xfce/$DEF_LINK_NAME | sed -r -n 's;^(.*/)?([[:alnum:]_]+)_[[:digit:]]+x[[:digit:]]+_[[:digit:]]+x[[:digit:]]+.*$;\2;p')"
[ -n "$BG_NAME" ] || exit 0

for b in $(find $destdir/usr/share/backgrounds/xfce/ -mindepth 1 -maxdepth 1 -xtype f -name "${BG_NAME}_*" -printf "%f\n"); do
	bg_size="$(echo "$b" | sed -n -r 's;[[:alnum:]_]+_([[:digit:]]+x[[:digit:]]+)_[[:digit:]]+x[[:digit:]]+\.[[:alpha:]]+$;\1;p')"
	[ -n "$bg_size" ] || continue
	if [ "$SIZE" = "$bg_size" ]; then
		NEW_DEFAULT="$b"
		break
	fi
done

if [ -z "$NEW_DEFAULT" ] || ! [ -e "$destdir/usr/share/backgrounds/xfce/$NEW_DEFAULT" ]; then
	exit 0
fi

ln -sf "$NEW_DEFAULT" "$destdir/usr/share/backgrounds/xfce/$DEF_LINK_NAME" ||:

# Change LDM background and default.png
for f in xdm default; do
	[ -e "$destdir/usr/share/design/slinux/backgrounds/$f-$SIZE.png" ] || continue
	ln -sf "$f-$SIZE.png" "$destdir/usr/share/design/slinux/backgrounds/$f.png" ||:
done
