#!/bin/bash

set -e

curlopts="-S"
branch="default"
server="screeps.com"

OPTIND=1
while getopts "he:s:vb:" opt ; do
    case "$opt" in
    h)
        echo "usage: $0 [options] [src]"
        echo 'options:'
        echo '  -h           print this help message'
        echo '  -e <email>   set email'
        echo '  -s <server>  set server (default is "screeps.com")'
        echo '  -v           verbose output'
        echo '  -b <branch>  set branch (default is "default")'
        exit
        ;;
    e) email="$OPTARG" ;;
    s) server="$OPTARG" ;;
    b) branch="$OPTARG" ;;
    v) curlopts="$curlopts -v" ;;
    esac
done
shift $((OPTIND-1))

src=${1:"src"}

if [ -z ${email+x} ] ; then read -p  "email: "    email ; fi
if [ -z ${pass+x}  ] ; then read -sp "password: " pass  ; fi
echo

(
echo '{"branch":"'"$branch"'",'
echo '"modules":{'
for f in "$src"/*.js ; do
    if [ ! -z ${file+x} ] ; then echo ',' ; fi
    file="$(basename -- $f)"
    base="${file%.*}"
    echo -n "\"$base\":\""
    < "$f" sed 's+["\\]+\\&+g' | sed 's/\t/\\t/g' | sed 'a\\\n' | tr -d '\n'
    echo -n '"'
done
echo
echo "}}"
) \
| curl \
    -H 'Content-Type: application/json; charset=utf-8' \
    --user "$email:$pass" \
    --data @- \
    --http1.1 \
    $curlopts "https://$server/api/user/code"

echo
