#!/run/current-system/sw/bin/bash

# Cron tasks
if type /run/current-system/sw/bin/nextcloud-occ 2>/dev/null; then
    /run/current-system/sw/bin/nextcloud-occ preview:pre-generate
    /run/current-system/sw/bin/nextcloud-occ face:background_job -t 900
fi

# Sync GDL stuff
root=/srv/pool/scrapping

cd $root || exit
set -- Aqp ElasticWind
for user in "$@"; do
    originDir=$root/$user
    destDir=/srv/pool/nextcloud/$user/files/Requested
    destDirDup=/srv/pool/nextcloud/$user/files/RequestedDupePlzCheckNDel
    if [ ! -d "$destDir" ]; then
        echo "$destDir does not exist, creating..."
        mkdir -p "$destDir"
    fi
    cd "$originDir" || exit
    find . -type f -not -name '*.part' | while read -r file; do
        destination=$destDir/"$(echo "$file" | sed "s/^\.\///")"
        destinationDup=$destDirDup/"$(echo "$file" | sed "s/^\.\///")"

        if [ ! -f "$destination" ]; then
            echo "Safe to move $(basename "$file")"
            if [ ! -d "$(dirname "$destination")" ]; then
                echo "Creating parent directory..."
                mkdir -p "$(dirname "$destination")"
            fi
            mv -n "$file" "$destination"
        else
            echo "Duplicated encountered $(basename "$file")"
            if [ ! -d "$(dirname "$destinationDup")" ]; then
                echo "Creating parent directory..."
                mkdir -p "$(dirname "$destinationDup")"
            fi
            mv -n "$file" "$destinationDup"
        fi

    done

    find ./ -mindepth 1 -type d -empty -delete

    chown "$(id -u nextcloud)":"$(id -g nextcloud)" -R "$destDir"
    find "$destDir" -type d -exec chmod -R 755 {} \;
    find "$destDir" -type f -exec chmod -R 644 {} \;

    if [ -d "$destDirDup" ]; then
        chown "$(id -u nextcloud)":"$(id -g nextcloud)" -R "$destDir"
        find "$destDirDup" -type d -exec chmod -R 755 {} \;
        find "$destDirDup" -type f -exec chmod -R 644 {} \;
    fi
    if type /run/current-system/sw/bin/nextcloud-occ 2>/dev/null; then
        /run/current-system/sw/bin/nextcloud-occ files:scan --all
    fi
done
