#!/bin/bash
# This file is part of the FUSS project.
# Copyright (C) 2022-2023 The FUSS Project <info@fuss.bz.it>
# Authors: Marco Marinello <contact-nohuman@marinello.bz.it>
#          Paolo Dongilli <dongilli@fuss.bz.it>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# Create a symlink from default.svg to fuss-10-wallpaper.png.
# We will update this symlink later on

#RELEASE=$(lsb_release -a | grep Release | cut -f 2)
RELEASE=$(dpkg -l base-files | grep ^ii | awk '{print $3}' | cut -d. -f 1)
LINK_FILE="/usr/share/fuss-artwork/wallpapers/fuss-wallpaper.svg"
CURRENT_LINK="$(readlink -f $LINK_FILE)"
EXPECTED_LINK="/usr/share/fuss-artwork/wallpapers/fuss-${RELEASE}-wallpaper.svg"
DAILY_DIR="/usr/share/fuss-artwork/wallpapers/daily"
MONTHLY_DIR="/usr/share/fuss-artwork/wallpapers/monthly"

if test -e "$MONTHLY_DIR/$(date +%Y_%m).png"; then
  EXPECTED_LINK="$MONTHLY_DIR/$(date +%Y_%m).png"
fi

if ls $DAILY_DIR/$(date +%Y_%m_*-*).png > /dev/null 2>&1 ; then
  for i in $(ls -1 $DAILY_DIR/$(date +%Y_%m_*-*).png); do
    DAY_MIN=$(echo $i | cut -d . -f 1 | cut -d / -f 7 | cut -d _ -f 3 | cut -d "-" -f 1 | sed 's/^0*//')
    DAY_MAX=$(echo $i | cut -d . -f 1 | cut -d / -f 7 | cut -d _ -f 3 | cut -d "-" -f 2 | sed 's/^0*//')
    TODAY=$(date +%d | sed "s/^0*//g")
    if [[ "$TODAY" -ge "$DAY_MIN" && "$TODAY" -le "$DAY_MAX" ]]; then 
      EXPECTED_LINK=$i
      break
    fi  
  done
fi

if test -e "$DAILY_DIR/$(date +%Y_%m_%d).png"; then
  EXPECTED_LINK="$DAILY_DIR/$(date +%Y_%m_%d).png"
fi

test "$CURRENT_LINK" = "$EXPECTED_LINK" && exit 0

rm -f "$LINK_FILE"
ln -s "$EXPECTED_LINK" "$LINK_FILE"

exit 0
