#!/bin/bash

# Get the input URL
url="$1"
echo "Input URL: $url"

# Remove vlc:// prefix
url="${url#vlc://}"
echo "After removing prefix: $url"

# Handle weblink format
if [[ $url =~ ^weblink/?\?url= ]]; then
  echo "Detect weblink format"
  url=${url#"${BASH_REMATCH[0]}"}
# Fix Chrome 130+ format
elif [[ $url =~ ^(https?|ftp|udp|mms|file)// ]]; then
    protocol=${BASH_REMATCH[1]}
    echo "Detect unfixed protocol $protocol"
    echo "Fixing Chrome 130+ format"
    url="$protocol:${url#$protocol}"
    echo "After fixing: $url"
fi

# Ensure spaces are encoded
url="${url// /%20}"
echo "Final URL: $url"

# Check protocol
if [[ ! $url =~ ^(https?|ftp|udp|mms|file):// ]]; then
  echo "protocol not allowed"
  exit 1
fi

# Launch VLC
echo "Launching VLC..."
vlc "$url" >/dev/null 2>&1 &

# Small delay to ensure VLC starts properly
# sleep 0.2
