#!/bin/bash
# Bash solution to mamund's maze problem \o/
# see http://amundsen.com/examples/misc/maze-client.html

MAZE=http://amundsen.com/examples/mazes/2d/five-by-five/

#---------------------------------------------------------------------
function message {
    echo "# $1" >&2
}
function output {
    echo $1
}

# -- Orientation rules -----------------------------------------------
function east {
    sed '
    s!^south!2 south!;
    s!^east!3 east!;
    s!^north!4 north!;
    s!^west!5 west!;'
}
function south {
    sed '
    s!^west!2 west!;
    s!^south!3 south!; 
    s!^east!4 east!; 
    s!^north!5 north!;'
}
function west {
    sed '
    s!^north!2 north!;
    s!^west!3 west!;
    s!^south!4 south!;
    s!^east!5 east!;'
}
function north {
    sed '
    s!^east!2 east!;
    s!^north!3 north!;
    s!^west!4 west!;
    s!^south!5 south!;'
}
function start_exit {
    sed '
    s!^exit!0 exit!;
    s!^start!1 north!;
    '
}
#---------------------------------------------------------------------

#---------------------------------------------------------------------
function get {
    # return the maze+xml from the given uri
    local uri="${1:?}"
    curl -sL --compressed \
        -H 'Accept: application/vnd.amundsen.maze+xml' \
        "$uri" |
        tr '\n' ' ' | tr -s ' '
}


#---------------------------------------------------------------------
function get_links {
    # return rel href for the given uri
    local uri="${1:?}"
    get "$uri" | grep -o '<link [^>]*/>' | tr "'" '"' |
    grep -v 'rel="current"' |
    while read line ; do
        echo $(get_rel "$line") $(get_href "$line")
    done
}
function get_href {
     echo "$1" | sed 's!.*href="\([^"]*\)".*!\1!'
}
function get_rel {
     echo "$1" | sed 's!.*rel="\([^"]*\)".*!\1!'
}

#---------------------------------------------------------------------
function select_next {
    # select the next direction
    local facing="${1:?}"
    local uri="${2:?}"
    get_links "$uri" | start_exit | $facing | sort -n | head -n 1
}

#---------------------------------------------------------------------
function find_path {
    # bring me to exit !
    local uri="${1:?}"
    local facing="${2:?}"
    local next=""
    local count=0
    while [ "$facing" != "exit" ] ; do
        message "$count: I'm at <$uri>"
        next="$(select_next "$facing" "$uri")"
        facing=$(echo $next | cut -d ' ' -f 2)
        uri=$(echo $next | cut -d ' ' -f 3)
        message "$count: going to <$uri>, facing $facing"
        output $uri
        count=$((count+1))
    done
    message "I'm free!"

}


find_path "${1:-$MAZE}" "${2:-cat}"

