#!/bin/bash

SRC_DIR="ori_photo"
DST_DIR="1st"

mkdir -p "$DST_DIR"

########################################
# 📦 1️⃣ 전체 파일 목록 수집
########################################

mapfile -t FILE_LIST < <(
    find "$SRC_DIR" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) | sort
)

TOTAL=${#FILE_LIST[@]}

if [ "$TOTAL" -eq 0 ]; then
    echo "파일이 없습니다."
    exit 1
fi

########################################
# 1️⃣ 복사 단계
########################################

echo "▶ 1단계: 파일 복사 시작"

COUNT=1

for FILE in "${FILE_LIST[@]}"
do
    OUTPUT="$DST_DIR/${COUNT}.jpg"
    cp "$FILE" "$OUTPUT"

    PERCENT=$((COUNT * 100 / TOTAL))
    printf "\r[1단계] %d / %d (%d%%)" "$COUNT" "$TOTAL" "$PERCENT"

    COUNT=$((COUNT+1))
done

echo
echo "✔ 1단계 완료"
echo "----------------------------------"

########################################
# 2️⃣ 날짜별 이동
########################################

echo "▶ 2단계: 날짜별 이동 시작"

cd "$DST_DIR" || exit 1

mapfile -t FLAT_LIST < <(ls *.jpg 2>/dev/null)
TOTAL2=${#FLAT_LIST[@]}
COUNT2=0

for FILE in "${FLAT_LIST[@]}"
do
    COUNT2=$((COUNT2+1))

    DATE=$(exiftool -s3 -DateTimeOriginal -d "%Y-%m-%d" "$FILE")

    if [ -z "$DATE" ]; then
        continue
    fi

    mkdir -p "$DATE"
    mv "$FILE" "$DATE/"

    PERCENT2=$((COUNT2 * 100 / TOTAL2))
    printf "\r[2단계] %d / %d (%d%%)" "$COUNT2" "$TOTAL2" "$PERCENT2"
done

echo
echo "✔ 2단계 완료"
echo "----------------------------------"

########################################
# 3️⃣ 날짜 폴더 내부 정렬
########################################

echo "▶ 3단계: 시간순 정렬 시작"

mapfile -t DIR_LIST < <(find . -maxdepth 1 -type d ! -path . | sort)
TOTAL3=${#DIR_LIST[@]}
COUNT3=0

for DIR in "${DIR_LIST[@]}"
do
    COUNT3=$((COUNT3+1))
    DIR_NAME=$(basename "$DIR")
    cd "$DIR_NAME" || continue

    exiftool -T -DateTimeOriginal -FileName *.jpg | sort > /tmp/sorted.txt

    BASE_INDEX=0
    PREV_TIME=""
    DUP_COUNT=0

    while IFS=$'\t' read -r DATETIME FILE; do

        if [ "$DATETIME" = "$PREV_TIME" ]; then
            DUP_COUNT=$((DUP_COUNT+1))
            NEWNAME="${BASE_INDEX}_${DUP_COUNT}.jpg"
        else
            BASE_INDEX=$((BASE_INDEX+1))
            DUP_COUNT=0
            NEWNAME="${BASE_INDEX}.jpg"
        fi

        mv -- "$FILE" "$NEWNAME"
        PREV_TIME="$DATETIME"

    done < /tmp/sorted.txt

    rm -f /tmp/sorted.txt
    cd ..

    PERCENT3=$((COUNT3 * 100 / TOTAL3))
    printf "\r[3단계] %d / %d (%d%%)" "$COUNT3" "$TOTAL3" "$PERCENT3"
done

echo
echo "✔ 3단계 완료"
echo "----------------------------------"

echo "✅ All done."
