#!/bin/bash

echo "=== Enzonix S3 Mount Script ==="

read -p "输入 Access Key: " ACCESS_KEY
read -p "输入 Secret Access Key: " SECRET_KEY
read -p "输入 Bucket 名称: " BUCKET_NAME
read -p "输入 S3 Endpoint（如 https://ny-1s.enzonix.com）: " S3_ENDPOINT
read -p "输入 S3 Region（如 us-east-1）: " REGION
read -p "输入本地挂载目录（如 /mnt/s3）: " MOUNT_PATH

REMOTE_NAME="enzonix"
RCLONE_CONFIG_DIR="/root/.config/rclone"
RCLONE_CONFIG_FILE="$RCLONE_CONFIG_DIR/rclone.conf"
SERVICE_FILE="/etc/systemd/system/rclone-s3.service"

# 安装 rclone（如果未安装）
if ! command -v rclone &> /dev/null; then
  echo "🔧 正在安装 rclone..."
  apt update && apt install -y rclone
fi

# 安装 fuse（如未安装）
if ! command -v fusermount &> /dev/null; then
  apt install -y fuse
fi

# 创建 rclone 配置目录
mkdir -p "$RCLONE_CONFIG_DIR"

# 写入配置文件
cat > "$RCLONE_CONFIG_FILE" <<EOF
[$REMOTE_NAME]
type = s3
provider = Other
access_key_id = $ACCESS_KEY
secret_access_key = $SECRET_KEY
endpoint = $S3_ENDPOINT
location_constraint = $REGION
acl = private
EOF

# 创建挂载目录
mkdir -p "$MOUNT_PATH"

# 生成 systemd 服务文件
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=Mount Enzonix S3 Bucket to $MOUNT_PATH
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
ExecStart=/usr/bin/rclone mount $REMOTE_NAME:$BUCKET_NAME $MOUNT_PATH \\
  --config=$RCLONE_CONFIG_FILE \\
  --vfs-cache-mode writes \\
  --allow-other \\
  --dir-cache-time 72h \\
  --poll-interval 15s \\
  --umask 002 \\
  --log-file /var/log/rclone-s3.log \\
  --log-level INFO
ExecStop=/bin/fusermount -u $MOUNT_PATH
Restart=on-failure
RestartSec=10

[Install]
WantedBy=default.target
EOF

# 启用并启动 systemd 服务
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable rclone-s3
systemctl restart rclone-s3

echo "✅ 已挂载：$BUCKET_NAME → $MOUNT_PATH"
echo "✅ systemd 已启用：开机自动挂载"
