#!/usr/bin/env bash

set -euo pipefail

REMOTE_HOST="aynish@talos.feralhosting.com"
REMOTE_PATH="private/transmission/data/"
LOCAL_PATH="/mnt/two/incoming"
TRACKING_FILE="/mnt/two/incoming/.downloaded_albums"
LOG_FILE="/mnt/two/incoming/download-log"

# Create tracking file if it doesn't exist
touch "$TRACKING_FILE"

# Get list of albums on remote server
echo "$(date): Checking for new albums on seedbox..." >>"$LOG_FILE"
REMOTE_ALBUMS=$(rsync --dry-run --list-only "$REMOTE_HOST:$REMOTE_PATH" | grep '^d' | awk '{$1=$2=$3=$4=""; sub(/^ +/, ""); print}' | grep -v '^\.') || true

if [ -z "$REMOTE_ALBUMS" ]; then
	echo "$(date): No albums found on remote server" >>"$LOG_FILE"
	exit 0
fi

# Check each album against tracking file
NEW_ALBUMS=""
while IFS= read -r album; do
	if [ -n "$album" ] && ! grep -qF "$album" "$TRACKING_FILE"; then
		NEW_ALBUMS="$NEW_ALBUMS$album\n"
		echo "$(date): Found new album: $album" >>"$LOG_FILE"
	fi
done <<<"$REMOTE_ALBUMS"

if [ -z "$NEW_ALBUMS" ]; then
	echo "$(date): No new albums to download" >>"$LOG_FILE"
	exit 0
fi

# Download new albums only
echo "$(date): Starting download of new albums..." >>"$LOG_FILE"
while IFS= read -r album; do
	if [ -n "$album" ]; then
		echo "$(date): Downloading $album" >>"$LOG_FILE"
		if rsync -r --log-file="$LOG_FILE" "$REMOTE_HOST:$REMOTE_PATH$album/" "$LOCAL_PATH/$album/"; then
			echo "$album" >>"$TRACKING_FILE"
			echo "$(date): Successfully downloaded $album" >>"$LOG_FILE"

			# Import to beets
			echo "$(date): Importing $album to beets..." >>"$LOG_FILE"
			# Set umask to allow group read/write access
			umask 002
			if beet -p fetchart import -m -l /home/anish/music.log -q -g "$LOCAL_PATH/$album"; then
				echo "$(date): Successfully imported $album to beets" >>"$LOG_FILE"
			else
				echo "$(date): Failed to import $album to beets" >>"$LOG_FILE"
			fi
		else
			echo "$(date): Failed to download $album" >>"$LOG_FILE"
		fi
	fi
done <<<"$(echo -e "$NEW_ALBUMS")"

echo "$(date): Music sync completed" >>"$LOG_FILE"
