#!/bin/bash

SRC="3st"
DEST="final"

SERVER="u260018028@145.79.28.106"
PORT="65002"
#PATH_REMOTE="~/domains/likewind.cloud/public_html/data/media/journey/argentina/2022/"
PATH_REMOTE="~/domains/likewind.cloud/public_html/data/media/journey/chile/2022/"

EXT="jpg"

mkdir -p "$DEST"

# final 디렉토리 초기화 (중요)
rm -f "$DEST"/*.$EXT

# 1️⃣ 가장 작은 숫자 찾기
a=$(ls "$SRC"/*.$EXT 2>/dev/null \
| xargs -n1 basename \
| sed 's/\..*//' \
| grep -E '^[0-9]+$' \
| sort -n \
| head -1)

# 숫자 없으면 1부터 시작
if [ -z "$a" ]; then
a=1
fi

echo "start number: $a"

# 2️⃣ 파일 복사
cp "$SRC"/*.$EXT "$DEST"/

cd "$DEST" || exit

# 3️⃣ 촬영 날짜 기준 정렬
mapfile -t files < <(
for f in *.$EXT
do
d=$(identify -format "%[EXIF:DateTimeOriginal]" "$f" 2>/dev/null)
echo "$d|$f"
done | sort | cut -d'|' -f2
)

n=$a
uploaded=""

for f in "${files[@]}"
do

new="${n}.${EXT}"

mv -f "$f" "$new"

chmod 644 "$new"

# 4️⃣ 서버 업로드
scp -P "$PORT" "$new" "$SERVER:$PATH_REMOTE"

uploaded="$uploaded
{{ :journey:chile:2022:${new}?nolink |}}"

n=$((n+1))

done

echo "$uploaded"

# 5️⃣ 클립보드 복사
if command -v xclip >/dev/null
then
echo "$uploaded" | xclip -selection clipboard
elif command -v wl-copy >/dev/null
then
echo "$uploaded" | wl-copy
fi
