#!/bin/bash

video_file_path=/data/alist/local/ytdl/video/
rclone_remote=office-wdd
rclone_log_path=/data/alist/local/ytdl/appdata/rclone-to-onedrive.log


build_duplicate_files() {
  path=$1
  namelist=('How Geography Made The US Ridiculously OP.f399.mp4.part'
    'How Geography Made The US Ridiculously OP.f399.mp4.ytdl'
    'How Geography Made The US Ridiculously OP.info.json'
    "Why Russia's Biggest Threat is Actually China.mp4"
  )
  for file in $namelist; do
      echo "$file"
      touch "$file"
  done
}

check_duplicate_filenames() {
    path=$1
    files=$(find $path -type f)
    if [ -z "$files" ]; then
      echo "there are no files in $path, continue waiting!"
      return 1
    fi
    duplicates=0
    for file in $files; do
        filename=$(basename $file)
        count=$(echo $filename | tr -cd '.' | wc -c)
        if [ $count -gt 1 ]; then
            echo "find duplicate files in $path, continue waiting!"
            duplicates=1
            break
        fi
    done
    return $duplicates
}

move_files_to_onedrive() {

    echo "[$(date --rfc-3339=seconds | cut -d"+" -f1 | sed "s/ /-/g" | sed "s/:/-/g")] start to move files [ $(find "$video_file_path" -type f -exec basename {} \;) ]  to OneDrive" >> $rclone_log_path

    rclone move "$video_file_path" "$rclone_remote":/TransVideos --create-empty-src-dirs -P >> $rclone_log_path

    echo "[$(date --rfc-3339=seconds | cut -d"+" -f1 | sed "s/ /-/g" | sed "s/:/-/g")]  move files [ $(find "$video_file_path" -type f -exec basename {} \;) ] to OneDrive complete!" >> $rclone_log_path

}


while true; do
    check_duplicate_filenames "$video_file_path"
    result=$?
    if [ $result -eq 0 ]; then
        move_files_to_onedrive
    else
        sleep 5
    fi
done