#!/bin/bash
# dolphin-ftp-share - Manage FTP folder shares for Dolphin
#
# Usage:
#   dolphin-ftp-share info                              List all shares
#   dolphin-ftp-share add <name> <path> <anon> <acl>    Add/update a share
#   dolphin-ftp-share delete <name>                     Remove a share
#
# Share configs are stored in ~/.local/share/dolphin-ftp-shares/
# Shares are bind-mounted into ~/.local/share/dolphin-ftp-root/
#
# The FTP root directory can be served by any FTP server (e.g. vsftpd).
# Each share appears as a real subdirectory under the FTP root via bind mount.

set -e

SHARE_DIR="${HOME}/.local/share/dolphin-ftp-shares"
FTP_ROOT="${HOME}/.local/share/dolphin-ftp-root"

cmd_info() {
    [ -d "$SHARE_DIR" ] || exit 0
    for conf in "$SHARE_DIR"/*.conf; do
        [ -f "$conf" ] || continue
        name=$(basename "$conf" .conf)
        echo "[$name]"
        cat "$conf"
        echo ""
    done
}

cmd_add() {
    local name="$1"
    local path="$2"
    local anon="$3"
    local acl="$4"

    if [ -z "$name" ] || [ -z "$path" ]; then
        echo "Error: name and path are required" >&2
        exit 1
    fi

    mkdir -p "$SHARE_DIR" "$FTP_ROOT"

    # Write share config
    cat > "$SHARE_DIR/$name.conf" <<EOF
path=$path
anonymous=$anon
user_acl=$acl
EOF

    # Create mount point directory
    mkdir -p "$FTP_ROOT/$name"

    # Unmount if already mounted
    mountpoint -q "$FTP_ROOT/$name" 2>/dev/null && sudo umount "$FTP_ROOT/$name" 2>/dev/null || true

    # Bind-mount the shared folder into the FTP root
    sudo mount --bind "$path" "$FTP_ROOT/$name"

    echo "Share '$name' added: $path -> $FTP_ROOT/$name"
}

cmd_delete() {
    local name="$1"

    if [ -z "$name" ]; then
        echo "Error: name is required" >&2
        exit 1
    fi

    # Unmount bind mount
    if mountpoint -q "$FTP_ROOT/$name" 2>/dev/null; then
        sudo umount "$FTP_ROOT/$name"
    fi

    rm -f "$SHARE_DIR/$name.conf"
    rmdir "$FTP_ROOT/$name" 2>/dev/null || true

    # Clean up empty directories
    rmdir "$SHARE_DIR" 2>/dev/null || true
    rmdir "$FTP_ROOT" 2>/dev/null || true

    echo "Share '$name' deleted"
}

case "${1:-}" in
    info)   cmd_info ;;
    add)    cmd_add "$2" "$3" "${4:-n}" "${5:-}" ;;
    delete) cmd_delete "$2" ;;
    *)
        echo "Usage: dolphin-ftp-share {info|add|delete}" >&2
        echo "" >&2
        echo "Commands:" >&2
        echo "  info                              List all shares" >&2
        echo "  add <name> <path> <anon> <acl>    Add/update a share" >&2
        echo "  delete <name>                     Remove a share" >&2
        exit 1
        ;;
esac
