#!/bin/bash

# git clone 函数
function git_clone_with_auth() {
    # 函数参数: $1 - Git仓库URL, $2 - 用户名, $3 - 密码, $4 - 克隆后的目录名
    local url="$1"
    local username="$2"
    local password="$3"
    local repo_name="$4"

    # 检查git命令是否存在
    if ! command -v git &> /dev/null; then
        echo "git 未安装, 请先安装"
        exit 1
    fi

    # 清理旧目录，如果存在
    if [ -d "$repo_name" ]; then
        echo "清理旧的克隆目录: $repo_name"
        rm -rf "$repo_name"
    fi
    mkdir "$repo_name"

    echo "git clone 开始 ..... "
    # 创建Base64编码的认证字符串
    local auth_header=$(echo -n "$username:$password" | base64)
    # 执行git clone命令，使用--config来设置HTTP头部
    git clone --config http.extraheader="Authorization: Basic $auth_header" "$url" "$repo_name"
}

# ftp 文件下载和MD5校验
function download_and_extract_zip(){
    local server=$1
    local port=$2
    local path=$3
    local user=$4
    local password=$5
    local expected_md5=$6
    local filename="${path##*/}"
    local file_app=$7

    # 检查curl 和 md5sum 是否被安装
    if ! command -v curl &> /dev/null || ! command -v md5sum &> /dev/null; then
        echo "Error: This script requires 'curl' and 'md5sum'. Please install them."
        return 1
    fi

    # 根据传参合成ftp url
    local ftp_url="ftp://${server}:${port}${path}"

    # 检查文件是否存在
    if [ -d "$file_app" ]; then
        echo "清理旧的解压目录: $file_app"
        rm -rf "$file_app"
    fi

    # 下载文件
    echo "下载文件从 ${ftp_url}"
    curl -u "${user}:${password}" -o "${filename}" "${ftp_url}"

    # 检查文件是否存在
    if [ ! -f "$filename" ]; then
        echo "Error: 下载失败. 文件不被发现."
        return 1
    fi

    # MD5检查
    local actual_md5=$(md5sum "$filename" | awk '{print $1}')

    if [ "$actual_md5" != "$expected_md5" ]; then
        echo "Error: MD5 校验失败. 文件也许是错误的."
        rm "$filename"
        return 1
    fi

    mkdir "$file_app"
    echo "下载后的文件位置 ${filename}..."
    unzip "$filename" -d "$file_app"
    chmod 777 "$file_app/${filename%.zip}"

    # 检查解压状态
    if [ $? -eq 0 ]; then
        echo "文件解压成功."
    else
        echo "Error: 解压失败."
        rm "$filename"
        return 1
    fi

    # Cleanup ZIP file
    rm "$filename"
    echo "zip 文件删除."

    return 0
}

setup_quectel() {
    local env=$1
    local zip_file="quectel-CM-binary-RK3568.zip"
    local bin_file="quectel-CM"
    local service_file="quectel-autodial.service"
    local extract_dir="${zip_file%.zip}"

    echo "4G驱动程序初始化.... "
    if [ ! -d "$env" ]; then
        echo "错误: 指定的环境目录 '$env' 不存在。"
        return 1
    fi

    local zip_path="${env}/${zip_file}"
    if [ ! -f "$zip_path" ]; then
        echo "错误: ZIP文件 '$zip_path' 不存在。"
        return 1
    fi

    local extract_path="${env}/${extract_dir}"
    if [ ! -d "$extract_path" ]; then
        echo "解压缩4G配置文件..."
        unzip "$zip_path" -d "$env"
    fi

    local bin_path="${extract_path}/${bin_file}"
    if [ ! -f "$bin_path" ]; then
        echo "错误:二进制文件 '$bin_path' 不存在。"
        return 1
    fi

    local service_path="${extract_path}/${service_file}"
    if [ ! -f "$service_path" ]; then
        echo "错误:service 文件 '$service_path' 不存在。"
        return 1
    fi

    chmod +x "$bin_path"
    sudo cp "$bin_path" /usr/sbin/
    sudo cp "$service_path" /lib/systemd/system/
    # sudo systemctl enable "$service_file"
    # sudo systemctl start "$service_file"
    rm -rf "$extract_path"
    echo "设置完成."
}

setup_frpc() {
    local env=$1
    local zip_file="frpc_0.59.0_linux_arm64.zip"   
    local extract_dir="${zip_file%.zip}"
    echo "frpc驱动程序初始化.... "
    if [ ! -d "$env" ]; then
        echo "错误: 指定的环境目录 '$env' 不存在。"
        return 1
    fi
    local zip_path="${env}/${zip_file}"
    if [ ! -f "$zip_path" ]; then
        echo "错误: ZIP文件 '$zip_path' 不存在。"
        return 1
    fi

    local extract_path="${env}/${extract_dir}"
    if [ ! -d "$extract_path" ]; then
        echo "解压缩frpc配置文件..."
        unzip "$zip_path" -d "$env"
    fi 
    chmod 777 "${extract_path}/frpc"
    sudo cp "${extract_path}/frpc" /usr/bin/
    chmod 777 "${extract_path}/mqtt_frpc"
    sudo cp "${extract_path}/mqtt_frpc" /usr/bin/
    sudo mkdir /etc/frp
    sudo cp "${extract_path}/frpc.toml" /etc/frp/
    sudo cp "${extract_path}/config.json" /etc/frp/  
    sudo cp "${extract_path}/mqtt_frpc.service" "/usr/lib/systemd/system/"
    sudo systemctl enable mqtt_frpc
    rm -rf "$extract_path"
    echo "设置完成."
}

setup_ssh() {
    local env=$1
    echo "ssh密钥设置.... "
    if [ ! -d "$env" ]; then
        echo "错误: 指定的环境目录 '$env' 不存在。"
        return 1
    fi
    mkdir -p ~/.ssh
    chmod 700 ~/.ssh
    cp "${env}/authorized_keys" ~/.ssh/authorized_keys
    chmod 600 ~/.ssh/authorized_keys  
    echo "设置完成."  
}
# Example usage of the function

if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
    bin_path="/home/linaro/wtdiagnose/"
    git_path="./source_code"
    echo "app 可执行文件下载成功"
    pwd
    if [ -d ${git_path} ]; then
        echo "app应用程序初始化正在操作....."
        cp -r "${git_path}/file" "${bin_path}"
        cp -r "${git_path}/db" "${bin_path}"
        cp "${git_path}/ftp_update" "${bin_path}"
        chmod 777 "${bin_path}/ftp_update"
        sudo cp "${git_path}/service/ftp_update.service" "/usr/lib/systemd/system/"
        sudo cp "${git_path}/service/frpc.service" "/usr/lib/systemd/system/"
        sudo cp "${git_path}/service/wtdiagnose.service" "/usr/lib/systemd/system/"
        echo "app应用程序初始化完成....."
        setup_quectel "${git_path}/env"  
        setup_frpc "${git_path}/env" 
        setup_ssh "${git_path}/env"
        echo "app应用程序初始化完成....."
        exit 0
    else
        echo "克隆失败."
        exit 1
    fi
fi