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

# Script Name: url
# Description: Parse URLs into component parts
# Source: https://evanhahn.com/scripts-i-wrote-that-i-use-all-the-time/
# Usage: url "https://user:pass@example.com:8080/path?query=1#fragment"

if [[ $# -eq 0 ]]; then
    echo "Usage: url <url>" >&2
    echo "Example: url 'https://example.com:8080/path?key=value#section'" >&2
    exit 1
fi

url="$1"
echo "original: $url"

# Parse URL using regex
if [[ $url =~ ^([a-z][a-z0-9+.-]*):(//)?(([^:/@]+)(:([^/@]+))?@)?([^/:?#]+)?(:([0-9]+))?(/[^?#]*)?(\\?([^#]*))?(#.*)? ]]; then
    scheme="${BASH_REMATCH[1]:-}"
    username="${BASH_REMATCH[4]:-}"
    password="${BASH_REMATCH[6]:-}"
    hostname="${BASH_REMATCH[7]:-}"
    port="${BASH_REMATCH[9]:-}"
    path="${BASH_REMATCH[10]:-}"
    query="${BASH_REMATCH[12]:-}"
    fragment="${BASH_REMATCH[14]:-}"
fi

echo "protocol: ${scheme:-}"
[[ -n "${username:-}" ]] && echo "username: $username"
[[ -n "${password:-}" ]] && echo "password: $password"
[[ -n "${hostname:-}" ]] && echo "hostname: $hostname"
[[ -n "${port:-}" ]] && echo "port: $port"
[[ -n "${path:-}" ]] && echo "path: $path"
[[ -n "${query:-}" ]] && echo "query: ${query#\?}"
[[ -n "${fragment:-}" ]] && echo "hash: ${fragment#\#}"
