#!/bin/bash

check_dependancies()
{
    if [ $# -eq 0 ] ; then
        if [[ $(bash --version | head -n 1 | cut -f 1 -d "." | tr -d "[:alpha:]") < "4" ]] ; then
            echo "This game requires bash version 4 or higher. Earlier versions may not be able to successfully run this code."
        fi
        if ! hash sox &> /dev/null ; then
            echo "The program sox is required but does not appear to be installed on your system. Please install sox and try
again."
            exit 1
        fi
    fi
    for i in $@ ; do
        if ! hash $i &> /dev/null ; then
            echo "The program $i is required but does not appear to be installed on your system. Please install $i and try
again."
            exit 1
        fi
    done
}

initialize_players()
{
    i=1
    while [ $i -le $1 ] ; do
        player[$i]=0
        let i++
    done
}

play_sound()
{
play -qV0 sounds/$@
}

check_dependancies
check_dependancies rolldice
#get terminal width
columns=$(tput cols)
play_sound intro.ogg
#find out how many players there are
if [ $# -gt 1 ] ; then
    echo "Usage: $0 or $0 number of players."
    exit 1
fi
if [ $# -eq 1 ] ; then
    if ! [[ "$1" =~ ^[0-9]+$ ]] ; then
        echo "The number of players must be a number, 2 or greater."
        exit 1
    fi
    if [ $1 -lt 2 ] ; then
        echo "The number of players must be a number, 2 or greater."
        exit 1
    fi
    totalPlayers=$1
else
    totalPlayers=2
    cpu=true
fi
initialize_players $totalPlayers
#determine who goes first.
playerIndex=$(rolldice 1d${#player[@]})
while [ $playerIndex -gt 0 ] ; do
    score_keeper $playerIndex
    let playerIndex++
    if [ $playerIndex -gt ${#player[@]} ] ; then
        playerIndex=1
    fi
done
exit 0
