#!/bin/bash

taskdir=`php /unas/apps/wanyoucloudserver/v3/components/func/getTaskDir.php`
# 输出结果
#echo "WebdavTempDir: $taskdir"

#conf_file="/unas/run/wanyoucloud/cp/$ID/conf"
#progress_file="/unas/run/wanyoucloud/cp/$ID/progress"
#done_file="/unas/run/wanyoucloud/cp/$ID/done"
#size_file="/unas/run/wanyoucloud/cp/$ID/size"
#processing_file="/unas/run/wanyoucloud/cp/$ID/processing"

params_str=$1
#params_str=admin-e29d0366220e221319a0ed1e969fea76e0d5e326dbd21c9318a1a5683dd49d7b
# 使用 cut 命令分割字符串
USER=$(echo "$params_str" | cut -d'-' -f1)
ID=$(echo "$params_str" | cut -d'-' -f2)
# 输出每个部分
#echo "Part 1: $USER"
#echo "Part 2: $ID"

conf_file="$taskdir/$USER/$ID/conf"
progress_file="$taskdir/$USER/$ID/progress"
done_file="$taskdir/$USER/$ID/done"
size_file="$taskdir/$USER/$ID/size"
processing_file="$taskdir/$USER/$ID/processing"
errorperm_file="$taskdir/$USER/$ID/errorperm"

if [ ! -f "$conf_file" ]; then
  exit 0;
fi

exec > $progress_file
. $conf_file

SIZES=(`du -bsc "${SOURCE[@]}"|awk '{print $1}'`)
TOTAL_SIZE=${SIZES[-1]}
SIZE_DONE=0
DONE_FLAG=0

copy(){
    source_file=$1
    target_file=$2
    if [ -f "$source_file" ];then
        dist="$target_file"
    else
        source_file="$source_file/"
        dist="$target_file/"
    fi

    if [ $USER == "admin" ];then
        rsync -aI --info=progress2 --chown=admin:Administrators "$source_file" "$dist"
        if [ $? -ne 0 ]; then
            DONE_FLAG=4
        fi
    else
        sudo -E -u $USER rsync -aI --info=progress2 "$source_file" "$dist"
        if [ $? -ne 0 ]; then
            DONE_FLAG=4
        fi
    fi
}

echo $SIZE_DONE $TOTAL_SIZE > $size_file

for i in "${!SOURCE[@]}";
do
    echo ${SIZES[$i]} "${SOURCE[$i]}" -\> "${TARGET[$i]}" > $processing_file
    copy "${SOURCE[$i]}" "${TARGET[$i]}"
#    SIZE_DONE=`expr $SIZE_DONE + ${SIZES[$i]}`
    SIZE_DONE=$((SIZE_DONE + ${SIZES[$i]:-0}))
    echo $SIZE_DONE $TOTAL_SIZE > $size_file
done

code=$?

echo $code > $done_file

if [ $DONE_FLAG -eq 4 ]; then
  echo $DONE_FLAG > $errorperm_file
  php /unas/apps/wanyoucloudserver/v3/components/func/updateTask.php -a "$ID" -b 2 # 0已完成，1进行中，2失败，3错误，4权限不足
else
  if [ $code -eq 0 ] && [ $DONE_FLAG -eq 0 ]; then
    php /unas/apps/wanyoucloudserver/v3/components/func/updateTask.php -a "$ID" -b 0
  fi
fi

rm $progress_file $size_file $processing_file

exit $code
