#!/bin/bash

#set -e

PROGNAME=$(basename $0)

# Conductor auth cookie file
CONDUCTOR_AUTH=.conductor_auth

usage () {
    echo \
"Usage: $PROGNAME [options] <package=version> <package=version> ...
Create conductor ticket to deploy specified packages.

Options:
  --host                Conductor host (default: c.yandex-team.ru)
  --branch              Conductor branch (default: testing)
  --auth                Conductor auth cookie (default: read from ~/$CONDUCTOR_AUTH and $CONDUCTOR_AUTH)
  --comment             Ticket comment
  --cc                  Add specified email to CC, can be used multiple times
  --skip-restart        Skip service restart (default: restart)
  --no-autoinstall      Do not use autoinstall (default: use)
  --help                Show this message
"
}

urlencode () {
    echo $(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' "$1")
}

createTicket () {
    local chost=$1
    local cauth=$2
    local branch=$3
    local comment=$(urlencode "$4")
    local mailcc=$(urlencode "$5")
    local skipRestart=$6
    local noAutoinstall=$7
    shift 7
    local curl_opts="--show-error \
    --user-agent 'conductor-ticket' \
    --header Accept=application/xml \
    -d ticket[branch]=$branch \
    -b conductor_auth=$cauth"

    if [ -n "$comment" ]; then
        curl_opts="$curl_opts -d ticket[comment]=$comment"
    fi

    if [ -n "$mailcc" ]; then
        curl_opts="$curl_opts -d ticket[mailcc]=$mailcc"
    fi

    if [ "$skipRestart" ]; then
        curl_opts="$curl_opts -d ticket[skip_restart]=1"
    fi

    if [ "$noAutoinstall" ]; then
        curl_opts="$curl_opts -d ticket[do_not_autoinstall]=1"
    fi

    i=0
    while [ $# -gt 0 ]; do
        local pack=($(echo $1 | tr "=" "\n"))
        curl_opts="$curl_opts -d package[$i]=${pack[0]} -d version[$i]=${pack[1]}"
        i=$((i + 1))
        shift
    done

    res=$(curl --silent --write-out "\n%{http_code}" "http://$chost/auth_update/ticket_add/" $curl_opts)
    retval=$?
    if [ $retval -ne 0 ]; then
        return $retval
    fi
    http_code=$(echo "$res" | tail -n 1)
    res=$(echo "$res" | head -n -1)
    #echo "$http_code"
    echo "$res"
    retval=0
    if [ "$http_code" -ne "200" ]; then
        retval=1
    fi
    return $retval
}

# Default Conductor host
chost=c.yandex-team.ru

# Default Conductor branch
cbranch=testing

# Conductor auth cookie
cauth=

# Ticket comment
ccomment=

# Skip service restart
cskipRestart=

# Do not use autoinstall
cnoAutoinstall=

# Also email
ccc=

# Ticket packages
cpackages=
pi=0
cci=0

# Parse command line args
while [ $# -gt 0 ]; do
    case "$1" in
        --*)
            # Parse opts
            case "$1" in
                --host=*)
                    chost=$(echo "$1" | sed -e 's/^--host=//; s%^http[s]*://%%g; s%\(.\)/$%\1%;') ;;
                --host)
                    shift; chost=$(echo "$1" | sed -e 's%^http[s]*://%%g; s%\(.\)/$%\1%;') ;;
                --auth=*)
                    cauth="`echo \"$1\" | sed -e 's/^--auth=//'`" ;;
                --auth)
                    shift; cauth=$1 ;;
                --branch=*)
                    cbranch="`echo \"$1\" | sed -e 's/^--branch=//'`" ;;
                --branch)
                    shift; cbranch=$1 ;;
                --comment=*)
                    ccomment="`echo \"$1\" | sed -e 's/^--comment=//'`" ;;
                --comment)
                    shift; ccomment=$1 ;;
                --cc=*)
                    ccc[$cci]="`echo \"$1\" | sed -e 's/^--cc=//'`"; cci=$((cci + 1)) ;;
                --cc)
                    shift; ccc[$cci]=$1; cci=$((cci + 1)) ;;
                --skip-restart) cskipRestart="yes" ;;
                --no-autoinstall) cnoAutoinstall="yes" ;;
                -h|--help) usage; exit 0 ;;
                *) echo "Wrong argument $1"; exit 1 ;;
            esac
            ;;
        *=*)
            cpackages[$pi]="$1"; pi=$((pi + 1)) ;;
        *)
            if [ "$2" == "="* ]; then
                cpackages[$pi]="$1$2"
            else
                cpackages[$pi]="$1=$2"
            fi
            shift; pi=$((pi + 1)) ;;
    esac
    shift
done

# Read conductor auth cookie from file if not specified in command line
if [ -z "$cauth" -a -e "$CONDUCTOR_AUTH" ]; then
    cauth=`cat $CONDUCTOR_AUTH`
fi
if [ -z "$cauth" -a -e "$HOME/$CONDUCTOR_AUTH" ]; then
    cauth=`cat $HOME/$CONDUCTOR_AUTH`
fi
if [ -z "$cauth" ]; then
    echo -e "conductor-auth is not set, you should specify it by using --auth argument"\
        "\nor paste it to the $CONDUCTOR_AUTH or ~/$CONDUCTOR_AUTH file" >&2
    exit 1
fi

if [ -z "${cpackages}" ]; then
    echo -e "packages to create ticket for are not specified\n"
    usage
    exit 1
fi

# join cc params to comma divided string
SAVE_IFS=$IFS
IFS=", "
cccStr="${ccc[*]}"
IFS=$SAVE_IFS

createTicket "$chost" "$cauth" "$cbranch" "$ccomment" "$cccStr" "$cskipRestart" "$cnoAutoinstall" ${cpackages[*]}
exit $?
