#!/bin/bash
# checkFile.sh — Move a downloaded file from tmp/ into the videos folder
#
# Called by getVideo.sh after yt-dlp or curl finishes downloading.
# Finds the first non-.part file in tmp/, converts it with ffmpeg if the
# extension doesn't match what was requested, then moves it to videos/{cat}/.
#
# Usage: checkFile.sh <ext> <cat>
#   ext  — expected extension (jpg or mp4)
#   cat  — playlist/category folder name under videos/

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
BASE_DIR="$(dirname "$SCRIPT_DIR")"

ext=$1
cat=$2


	
	TMP_DIR="$SCRIPT_DIR/tmp"

	# find file in tmp, ignoring .part files
	file=$(ls "$TMP_DIR" | grep -v '\.part$' | head -1)

	if [ -z "$file" ]; then
		echo "Error: no file found in $TMP_DIR (may still be downloading)"
		exit 1
	fi

	echo checking file: $file

	filename=$(basename -- "$file")
	extension="${filename##*.}"
	filename="${filename%.*}"

if [ "$extension" = "$ext" ]; then
  newFile=$file
else
  echo "not $ext (found .$extension) - converting with ffmpeg"
  newFile=$filename.$ext
  echo ffmpeg -i "$TMP_DIR/$file" "$TMP_DIR/$newFile"
  ffmpeg -i "$TMP_DIR/$file" "$TMP_DIR/$newFile"
  if [ $? -ne 0 ]; then
    echo "Error: ffmpeg conversion failed"
    exit 1
  fi
  rm "$TMP_DIR/$file"
fi

	echo ls "$TMP_DIR/"
	ls "$TMP_DIR/"
	echo mv "$TMP_DIR/$newFile" "$BASE_DIR/videos/$cat/"
	mv "$TMP_DIR/$newFile" "$BASE_DIR/videos/$cat/"

	echo ls "$BASE_DIR/videos/$cat/$filename.*"
	ls "$BASE_DIR/videos/$cat/$filename."*
	
#	files=(tmp/*)
#	if [ ${#files[@]} -gt 0 ]; then rm tmp/*.*; fi
