#!/bin/bash

BASEURL="http://127.0.0.1:8081/admin"
GEN_CERTS=0
GEN_PASSWD=0
EXTRA_TEAMS=0
CSV_SPLITER=","
CSV_COL_LASTNAME=2
CSV_COL_FIRSTNAME=3
CSV_COL_NICKNAME=5
CSV_COL_COMPANY=6
CSV_COL_TEAM=1

usage() {
    echo "$0 [options] csv_file"
    echo "    -B -baseurl BASEURL       URL to administration endpoint (default: $BASEURL)"
    echo "    -S -csv-spliter SEP       CSV separator (default: $CSV_SPLITER)"
    echo "    -e -extra-teams NBS       Number of extra teams to generate (default: ${EXTRA_TEAMS})"
    echo "    -c -generate-certificate  Should team certificates be generated? (default: no)"
    echo "    -p -generate-password     Should generate team password to teams.pass? (default: no)"
}

# Parse options
while [ "${1:0:1}" = "-" ]
do
    case "$1" in
	-B|-baseurl)
	    BASEURL=$2
	    shift;;
	-S|-csv-spliter)
	    CSV_SPLITER=$2
	    shift;;
	-e|-extra-teams)
	    EXTRA_TEAMS=$2
	    shift;;
	-c|-generate-certificates)
	    GEN_CERTS=1;;
	-p|-generate-password)
	    GEN_PASSWD=1;;
	*)
	    echo "Unknown option '$1'"
	    usage
	    exit 1;;
    esac
    shift
done

[ "$#" -lt 1 ] && [ "${EXTRA_TEAMS}" -eq 0 ] && { usage; exit 1; }

new_team() {
    head -n "$1" team-names.txt | tail -1 | sed -E 's/^.*\|\[\[([^|]+\|)?([^|]+)\]\][^|]*\|([A-Fa-f0-9]{1,2})\|([A-Fa-f0-9]{1,2})\|([A-Fa-f0-9]{1,2})\|([0-9]{1,3})\|([0-9]{1,3})\|([0-9]{1,3})\|.*$/\6 \7 \8 \2/' |
	while read line;
	do
	    R=`echo $line | cut -d " " -f 1`
	    G=`echo $line | cut -d " " -f 2`
	    B=`echo $line | cut -d " " -f 3`
	    if [ -z "$2" ]; then
		N=`echo $line | cut -d " " -f 4`
	    else
		N=`echo -n $2 | tr -d '\r\n'`
	    fi

	    COLOR=$((($R*256 + $G) * 256 + $B))

	    curl -s -d "{\"name\": \"$N\",\"color\": $COLOR}" "${BASEURL}/api/teams"
	done | grep -Eo '"id":[0-9]+,' | grep -Eo "[0-9]+"
}

TNUM=0

for i in $(seq $EXTRA_TEAMS)
do
    TNUM=$(($TNUM + 1))

    echo "Doing extra team $TNUM..."

    TID=`new_team $TNUM`

    if [ "${GEN_CERTS}" -eq 1 ] && ! curl -s -f "${BASEURL}/api/teams/${TID}/certificate" > /dev/null
    then
	curl -s -f "${BASEURL}/api/teams/${TID}/certificate/generate"
    elif [ "${GEN_PASSWD}" -eq 1 ]
    then
        TEAMID=$(curl -s -f "${BASEURL}/api/teams/${TID}/" | jq -r .name)
        PASSWD=$(curl -X POST -s -f "${BASEURL}/api/teams/${TID}/password" | jq -r .password)
	NP=$(echo "${TEAMID}" | cut -d : -f 1 | sed 's/[[:upper:]]/\l&/g;s/[âáàä]/a/g;s/[êéèë]/e/g')
	cat >> teams.pass <<EOF
${TEAMID}:${PASSWD}
EOF
	SALT="$(openssl rand -base64 3)"
	HASHED="{SSHA}$(echo -n $PASSWD$SALT | openssl dgst -binary -sha1 | sed 's#$#'"$SALT"'#' | base64)"
	cat >> htpasswd.ssha <<EOF
${NP}:${HASHED}
EOF
	HASHED="$(echo -n $PASSWD | openssl passwd -apr1 -in -)"
	cat >> htpasswd.apr1 <<EOF
${NP}:${HASHED}
EOF
    fi
    echo
done

[ "$#" -lt 1 ] && exit 0
PART_FILE="$1"

TMAX=`cat "$PART_FILE" | cut -d "${CSV_SPLITER}" -f $CSV_COL_TEAM | sort | uniq | wc -l`
TMAX=$(($TMAX + $TNUM))
cat "$PART_FILE" | cut -d "${CSV_SPLITER}" -f $CSV_COL_TEAM | sort | uniq | while read TEAMID
do
    TNUM=$(($TNUM + 1))

    echo "Doing team $TNUM/$TMAX ("$(($TNUM*100/$TMAX))"%)..."

    TID=`new_team "${TNUM}" "${TEAMID}"`

    if ! (
	echo -n "["
	HAS_MEMBER=1
	grep "${TEAMID}${CSV_SPLITER}" "$PART_FILE" | while read MEMBER
	do
	    LASTNAME=`echo $MEMBER | cut -d "${CSV_SPLITER}" -f $CSV_COL_LASTNAME | tr -d "\r\n"`
	    FIRSTNAME=`echo $MEMBER | cut -d "${CSV_SPLITER}" -f $CSV_COL_FIRSTNAME | tr -d "\r\n"`
	    NICKNAME=`echo $MEMBER | cut -d "${CSV_SPLITER}" -f $CSV_COL_NICKNAME | tr -d "\r\n"`
	    COMPANY=`echo $MEMBER | cut -d "${CSV_SPLITER}" -f $CSV_COL_COMPANY | tr -d "\r\n"`

	    if [ $HAS_MEMBER = 0 ]
	    then
		echo -n ,
	    else
		HAS_MEMBER=0
	    fi

	    cat <<EOF
{
  "firstname": "$FIRSTNAME",
  "lastname": "$LASTNAME",
  "nickname": "$NICKNAME",
  "company": "$COMPANY"
}
EOF
	done
	echo "]"
    ) | curl -f -s -d @- "${BASEURL}/api/teams/${TID}/members"
    then
	echo "An error occured"
    elif [ "${GEN_CERTS}" -eq 1 ] && ! curl -s -f "${BASEURL}/api/teams/${TID}/certificate" > /dev/null
    then
	curl -s -f "${BASEURL}/api/teams/${TID}/certificate/generate"
    elif [ "${GEN_PASSWD}" -eq 1 ]
    then
        PASSWD=$(curl -X POST -s -f "${BASEURL}/api/teams/${TID}/password" | jq -r .password)
	NP=$(echo "${TEAMID}" | cut -d : -f 1 | sed 's/[[:upper:]]/\l&/g;s/[âáàä]/a/g;s/[êéèë]/e/g')
	cat >> teams.pass <<EOF
${TEAMID}:${PASSWD}
EOF
	SALT="$(openssl rand -base64 3)"
	HASHED="{SSHA}$(echo -n $PASSWD$SALT | openssl dgst -binary -sha1 | sed 's#$#'"$SALT"'#' | base64)"
	cat >> htpasswd.ssha <<EOF
${NP}:${HASHED}
EOF
	HASHED="$(echo -n $PASSWD | openssl passwd -apr1 -in -)"
	cat >> htpasswd.apr1 <<EOF
${NP}:${HASHED}
EOF
    fi
    echo
done
