#!/usr/bin/env bash
set -e

# Get script name
script=$(basename "$0")
version="1.0.0"

# Display Help
help() {
    echo
    echo "$script"
    echo
    echo "Description: Parse and output segements."
    echo "Syntax: $script <url> [url|proto|user|pass|hostname|subdomain|port|path]"
    echo "Example: $script https://www.example.com subdomain,hostname"
    echo "         $script git@github.com:OCA/server-tools.git user,hostname,path"
    echo
}

# Show help and exit
if [[ "$1" == "help" ]]; then
    help
    exit
fi

# Check params
if [[ -z "$2" ]]; then
    echo "Parameter filter is empty."
    exit 1
fi

# Initialize variables
proto=""
user=""
pass=""
hostname=""
port=""
path=""
subdomain=""

# Check if the URL is in SSH format (e.g., git@github.com:OCA/server-tools.git)
if [[ "$1" == *:* && "$1" != *://* ]]; then
    proto="ssh://"
    user="$(echo "$1" | cut -d@ -f1)"
    hostname="$(echo "$1" | cut -d@ -f2 | cut -d: -f1)"
    path="$(echo "$1" | cut -d: -f2)"
else
    # Extract protocol
    proto="$(echo "$1" | grep :// | sed -e's,^\(.*://\).*,\1,g')"

    # Remove the protocol
    url="$(echo "${1/$proto/}")"

    # Extract the user (if any)
    userpass="$(echo "$url" | grep @ | cut -d@ -f1)"
    pass="$(echo "$userpass" | grep : | cut -d: -f2)"
    if [[ -n "$pass" ]]; then
        user="$(echo "$userpass" | grep : | cut -d: -f1)"
    else
        user=$userpass
    fi

    # Extract the hostname
    hostname="$(echo "${url/$user@/}" | cut -d/ -f1)"

    # Try to extract the port
    port="$(echo "$hostname" | sed -e 's,^.*:,:,g' -e 's,.*:\([0-9]*\).*,\1,g' -e 's,[^0-9],,g')"

    # Extract the path
    path="$(echo "$url" | grep / | cut -d/ -f2-)"

    # Extract subdomain (if any)
    if [[ "$hostname" == *.* ]]; then
        levels=$(echo "$hostname" | grep -o "\." | wc -l)
        if (( levels == 2 )); then
            subdomain=$(echo "$hostname" | awk -F"." '{print $1}')
        fi
    fi
fi

# Process the requested filters
for f in $(echo "$2" | sed "s/,/ /g")
do
    case $f in
        url)
            echo "$1"
            ;;
        proto)
            echo "$proto"
            ;;
        user)
            echo "$user"
            ;;
        pass)
            echo "$pass"
            ;;
        hostname)
            echo "$hostname"
            ;;
        subdomain)
            echo "$subdomain"
            ;;
        port)
            echo "$port"
            ;;
        path)
            echo "$path"
            ;;
    esac
done
