#!/usr/bin/env bash
set -euo pipefail

# ---- Mount game_drive on boot ----
UUID=$(blkid -s UUID -o value /dev/nvme0n1p1)
MOUNT_POINT="/mnt/game_drive"
sudo mkdir -p "$MOUNT_POINT"

# Add fstab entry if missing
if ! grep -q "$UUID" /etc/fstab; then
  echo "UUID=$UUID $MOUNT_POINT ext4 defaults,noatime,uid=1000,gid=1000 0 2" | sudo tee -a /etc/fstab
fi

sudo mount -a

# Ensure permissions are correct for user
sudo chown -R 1000:1000 "$MOUNT_POINT"

# ---- Permissions for user anon ----
sudo chown -R 1000:1000 /mnt/game_drive

# ---- Ensure LightDM autologin + session config ----
LIGHTDM_CONF="/etc/lightdm/lightdm.conf"
sudo mkdir -p /etc/lightdm

# Create file if it doesn't exist
if [ ! -f "$LIGHTDM_CONF" ]; then
  sudo tee "$LIGHTDM_CONF" >/dev/null <<'EOF'
[Seat:*]
autologin-user=anon
autologin-user-timeout=0
EOF
fi

# Add optional lines safely if missing
grep -q "^greeter-session=" "$LIGHTDM_CONF" 2>/dev/null || \
  echo "greeter-session=lightdm-gtk-greeter" | sudo tee -a "$LIGHTDM_CONF"

grep -q "^user-session=" "$LIGHTDM_CONF" 2>/dev/null || \
  echo "user-session=xfce" | sudo tee -a "$LIGHTDM_CONF"

sudo systemctl enable lightdm

# ---- Autostart Sunshine with 2s delay ----
AUTOSTART_DIR="$HOME/.config/autostart"
mkdir -p "$AUTOSTART_DIR"

SUNSHINE_DESKTOP="$AUTOSTART_DIR/sunshine.desktop"

cat > "$SUNSHINE_DESKTOP" <<'EOF'
[Desktop Entry]
Type=Application
Name=Sunshine
Exec=bash -c "sleep 2 && sunshine"
X-GNOME-Autostart-enabled=true
NoDisplay=false
Comment=Start Sunshine 2 seconds after login
EOF

# Ensure ownership for user Anon
chown 1000:1000 "$SUNSHINE_DESKTOP"

cd "$HOME"

# ---- Download Linux_CRU ----
CRU_FILE="$HOME/Linux_CRU-x86_64.AppImage"
if [ ! -f "$CRU_FILE" ]; then
    curl -L "https://v41h4114.online/public_assets/linux/Linux_CRU-x86_64.AppImage" -o "$CRU_FILE"
    chmod +x "$CRU_FILE"
fi

# ---- Extract AppImage contents ----
CRU_EXTRACT_DIR="$HOME/Linux_CRU_extracted"
mkdir -p "$CRU_EXTRACT_DIR"
# Only extract if folder is empty
if [ ! -f "$CRU_EXTRACT_DIR/AppRun" ]; then
    # Most AppImages support the --appimage-extract option
    "$CRU_FILE" --appimage-extract
    mv squashfs-root "$CRU_EXTRACT_DIR"
fi

# ---- Install python3-tkinter ----
sudo dnf -y install python3-tkinter

# ---- Download ReShade script ----
RESH_FILE="$HOME/reshade-linux.sh"
if [ ! -f "$RESH_FILE" ]; then
    curl -LO "https://github.com/kevinlekiller/reshade-steam-proton/raw/main/reshade-linux.sh" -o "$RESH_FILE"
    chmod u+x "$RESH_FILE"
fi

echo "Drive mounted and auto-login for user anon configured."