#!/bin/bash

# FTP 服务器信息
FTP_SERVER="wtlink.witium.com"
FTP_USER="witium"
FTP_PASSWORD="Huidu37774020"
CURRENT_DIR="/"
# 检查 lftp 和 dialog 是否安装
if ! command -v lftp &> /dev/null; then
    echo "lftp 未安装，请先安装 lftp。"
    exit 1
fi

if ! command -v dialog &> /dev/null; then
    echo "dialog 未安装，请先安装 dialog。"
    exit 1
fi

# 获取指定目录下的 FTP 列表
function get_ftp_list {
    local dir="$1"
    lftp -u "$FTP_USER","$FTP_PASSWORD" "$FTP_SERVER" <<EOF
cd "$dir"
ls
bye
EOF
}

# 显示菜单供用户选择
function show_menu {
    local list="$1"
    local -a items=()
    local line
    local name
    local type

    # 添加返回上一级目录选项
    if [ "$CURRENT_DIR" != "/" ]; then
        items+=(".." "返回上一级目录")
    fi

    while IFS= read -r line; do
        type=$(echo "$line" | awk '{print substr($1, 1, 1)}')
        name=$(echo "$line" | awk '{print $NF}')
        if [ "$type" = "d" ]; then
            items+=("$name" "文件夹")
        elif [ "$type" = "-" ]; then
            items+=("$name" "文件")
        fi
    done <<< "$list"

    selected=$(dialog --stdout --menu "当前目录: $CURRENT_DIR" 20 60 10 "${items[@]}")
    echo "$selected"
}

while true; do
    # 获取当前目录下的文件列表
    file_list=$(get_ftp_list "$CURRENT_DIR")
    # 显示菜单并获取用户选择
    selected=$(show_menu "$file_list")

    if [ -z "$selected" ]; then
        # 用户取消操作，退出脚本
        break
    elif [ "$selected" = ".." ]; then
        # 返回上一级目录
        CURRENT_DIR=$(dirname "$CURRENT_DIR")
        if [ "$CURRENT_DIR" = "." ]; then
            CURRENT_DIR="/"
        fi
    elif [[ $(echo "$file_list" | grep " $selected$" | awk '{print substr($1, 1, 1)}') = "d" ]]; then
        # 进入文件夹
        CURRENT_DIR="$CURRENT_DIR/$selected/"
        if [ "$CURRENT_DIR" != "/" ]; then
            CURRENT_DIR=$(realpath -m "$CURRENT_DIR")
        fi
    else
        # 下载文件
        echo "正在下载文件: $CURRENT_DIR/$selected"
        lftp -u "$FTP_USER","$FTP_PASSWORD" "$FTP_SERVER" <<EOF
get "$CURRENT_DIR/$selected"
bye
EOF
        if [ $? -eq 0 ]; then
            echo "文件下载成功。"
        else
            echo "文件下载失败。"
        fi
    fi
done