#!/bin/bash
# Configure USB automount support
set -euo pipefail

echo "Configuring USB automount support..."

# Create udev rules for USB devices
mkdir -p /etc/udev/rules.d

cat >/etc/udev/rules.d/99-usb-automount.rules <<'EOF'
# USB automount rules for KNEL-Football
ACTION=="add", SUBSYSTEM=="block", ENV{ID_FS_USAGE}=="filesystem", RUN+="/usr/local/bin/usb-automount.sh %k"
ACTION=="remove", SUBSYSTEM=="block", RUN+="/usr/local/bin/usb-unmount.sh %k"
EOF

# Create USB automount script
cat >/usr/local/bin/usb-automount.sh <<'EOF'
#!/bin/bash
# USB automount script
set -euo pipefail

DEVICE="/dev/${1}"
DEVICE_NAME="${1}"
MOUNT_BASE="/media/usb-${DEVICE_NAME}"

# Create mount point if it doesn't exist
mkdir -p "${MOUNT_BASE}"

# Determine filesystem type and mount with appropriate options
if blkid "${DEVICE}" | grep -q "TYPE=\"vfat\""; then
    mount -t vfat -o rw,uid=1000,gid=1000,dmask=000,fmask=111 "${DEVICE}" "${MOUNT_BASE}"
elif blkid "${DEVICE}" | grep -q "TYPE=\"ntfs\""; then
    mount -t ntfs-3g -o rw,uid=1000,gid=1000,dmask=000,fmask=111 "${DEVICE}" "${MOUNT_BASE}"
elif blkid "${DEVICE}" | grep -q "TYPE=\"ext4\""; then
    mount -t ext4 -o rw "${DEVICE}" "${MOUNT_BASE}"
else
    mount -t auto -o rw,uid=1000,gid=1000 "${DEVICE}" "${MOUNT_BASE}"
fi

echo "USB device ${DEVICE} mounted at ${MOUNT_BASE}"
EOF

# Create USB unmount script
cat >/usr/local/bin/usb-unmount.sh <<'EOF'
#!/bin/bash
# USB unmount script
set -euo pipefail

DEVICE_NAME="${1}"
MOUNT_BASE="/media/usb-${DEVICE_NAME}"

# Unmount if mounted
if mountpoint -q "${MOUNT_BASE}"; then
    umount "${MOUNT_BASE}"
    rmdir "${MOUNT_BASE}"
    echo "USB device ${DEVICE_NAME} unmounted"
fi
EOF

# Make scripts executable
chmod +x /usr/local/bin/usb-automount.sh
chmod +x /usr/local/bin/usb-unmount.sh

# Add user to plugdev group for USB access
usermod -a -G plugdev football 2>/dev/null || true

# Create PCManFM configuration for better file management
mkdir -p /etc/skel/.config/pcmanfm
cat >/etc/skel/.config/pcmanfm/default/pcmanfm.conf <<'EOF'
[config]
bm_open_method=0
su_cmd=xdg-su -c '%s'

[volume]
mount_on_startup=0
mount_removable=1
autorun=0

[ui]
always_show_tabs=0
hide_close_btn=0
win_width=640
win_height=480

[desktop]
show_wallpaper=0
wallpaper_mode=0
wallpaper_file=
wallpaper_common=1
desktop_bg=#000000
desktop_fg=#ffffff
desktop_shadow=#ffffff
desktop_font="Sans 12"
show_wm_menu=1
show_documents=1
show_trash=1
show_mounts=1
EOF

echo "USB automount support configured successfully."
