#!/usr/bin/env bash

set -e
set -o pipefail

PRIVATE_TOKEN="${GITLAB_PRIVATE_TOKEN:-$(pass show majordomo/private/gitlab.intr/tokens/pyhalov)}"
PROJECT_NAME="${GITLAB_PROJECT_NAME:-$(basename "$PWD")}"
PROJECT_GROUP="${GITLAB_GROUP_NAME:-$(basename "$(dirname "$PWD")")}"
PROJECT_ID="${GITLAB_GROUP_ID:-$(curl --header 'Content-Type: application/json' --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "https://gitlab.intr/api/v4/projects/$PROJECT_GROUP%2F$PROJECT_NAME" | jq .id)}"
ASSIGNEE_USER="${GITLAB_ASSIGNEE_USER:-lyashenko}"
SQUASH="${GITLAB_SQUASH:-false}"
BROWSE="${GITLAB_BROWSE:-true}"
BRANCH="${GITLAB_BRANCH:-$(git branch --show-current)}"
TITLE="${GITLAB_TITLE:-$(git log -1 --format=%s)}"

NOTIFY_SLACK_ENABLE="${GITLAB_NOTIFY_SLACK_ENABLE:-false}"
NOTIFY_SLACK_USERNAME="${GITLAB_NOTIFY_SLACK_USERNAME:-here}"
NOTIFY_SLACK_CHANNEL="${GITLAB_NOTIFY_SLACK_CHANNEL:-#mjd_eng}"

assignee_id()
{
    curl --verbose --header "Content-Type: application/json" \
         --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" \
         "https://gitlab.intr/api/v4/users?active=true" \
        | jq --raw-output ".[] | select(.username == \"$1\") | .id"
}

merge_request()
{
    curl --verbose --request POST --header 'Content-Type: application/json' --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "https://gitlab.intr/api/v4/projects/$PROJECT_ID/merge_requests" --data "{\"source_branch\": \"${BRANCH}\", \"target_branch\": \"${GITLAB_TARGET_BRANCH:-master}\", \"title\": \"$TITLE\", \"assignee_id\": \"$ASSIGNEE_ID\", \"remove_source_branch\": \"true\", \"squash\": \"$SQUASH\"}"
}

case "$1" in
    merge)
        ASSIGNEE_ID="${GITLAB_ASSIGNEE_ID:-$(assignee_id "$ASSIGNEE_USER")}"
        web_url="$(merge_request | jq --raw-output .web_url)"
        echo "$web_url" | xclip -i -sel p -f | xclip -i -sel c
        if [[ "$web_url" == http* ]]
        then
            if [[ $BROWSE == true ]]
            then
                "${BROWSER:-firefox}" "$web_url"
            fi
            if [[ $NOTIFY_SLACK_ENABLE == true ]]
            then
                ansible-playbook -i localhost, -c local /dev/stdin <<EOF
- hosts: localhost
  tasks:
  - name: Send notification message via Slack
    slack:
      channel: '${NOTIFY_SLACK_CHANNEL}'
      username: "Олег Пыхалов"
      icon_url: "https://ca.slack-edge.com/T2NPT97BM-U02GLBYEFG8-bbeb9604d056-192"
      token: '$(pass show majordomo/private/slack.com/token/hr)'
      msg: @${NOTIFY_SLACK_USERNAME} ${web_url}
    delegate_to: localhost
EOF
            fi
        else
            printf "'%s' is not a HTTP URL.\n" "$web_url"
        fi
        ;;
    repository)
        chromium "https://gitlab.intr/${PROJECT_GROUP}/${PROJECT_NAME}/-/settings/repository"
        ;;
    *)
        "${BROWSER:-firefox}" https://gitlab.intr/"$(basename "$(dirname "$PWD")")"/"$(basename "$PWD")"
        ;;
esac
