#!/bin/bash
set -e

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

# Display Help
Help() {
    echo
    echo "$SCRIPT"
    echo
    echo "Description: Filter URL for segments."
    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
[[ -z "$2" ]] && { echo "Parameter filter is empty." ; exit 1; }

# 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 -eq "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
