#!/usr/bin/env bash

WEBHOOK_URL="https://open.larksuite.com/open-apis/bot/v2/hook/3acf274a-1828-494b-a4a2-a3185f5e466d"

set -u

EVENT=""
SERVICE_NAME=""
NAMESPACE=""
IMAGE_REPO=""
IMAGE_TAG=""
VERSION_TAG=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --event)
      EVENT="$2"
      shift 2
      ;;
    --service-name)
      SERVICE_NAME="$2"
      shift 2
      ;;
    --namespace)
      NAMESPACE="$2"
      shift 2
      ;;
    --image-repo)
      IMAGE_REPO="$2"
      shift 2
      ;;
    --image-tag)
      IMAGE_TAG="$2"
      shift 2
      ;;
    --version-tag)
      VERSION_TAG="$2"
      shift 2
      ;;
    *)
      echo "Unknown argument: $1"
      exit 1
      ;;
  esac
done

escape_json() {
  python3 -c 'import json,sys; print(json.dumps(sys.stdin.read())[1:-1])'
}

commit_message() {
  git log -1 --pretty=%s
}

header_color() {
  case "$CIRCLE_BRANCH" in
    dev)
      echo "green"
      ;;
    staging)
      echo "blue"
      ;;
    prod)
      echo "red"
      ;;
    onprem-dev)
      echo "orange"
      ;;
    onprem-release)
      echo "purple"
      ;;
    *)
      echo "grey"
      ;;
  esac
}

build_deploy_payload() {
  local color="$1"
  local short_sha="${CIRCLE_SHA1:0:8}"
  local message
  local username
  local branch
  local job
  local service_name
  local namespace
  local image
  local commit
  local full_sha

  message=$(commit_message | escape_json)
  username=$(printf '%s' "$CIRCLE_USERNAME" | escape_json)
  branch=$(printf '%s' "$CIRCLE_BRANCH" | escape_json)
  job=$(printf '%s' "$CIRCLE_JOB" | escape_json)
  service_name=$(printf '%s' "$SERVICE_NAME" | escape_json)
  namespace=$(printf '%s' "$NAMESPACE" | escape_json)
  if [[ -n "$IMAGE_REPO" && -n "$VERSION_TAG" ]]; then
    image=$(printf '%s' "$IMAGE_REPO:$VERSION_TAG" | escape_json)
  else
    image="-"
  fi
  commit=$(printf '%s' "$short_sha" | escape_json)
  full_sha=$(printf '%s' "$CIRCLE_SHA1" | escape_json)

  cat <<EOF
{
  "msg_type": "interactive",
  "card": {
    "config": {
      "wide_screen_mode": true
    },
    "header": {
      "template": "${color}",
      "title": {
        "tag": "plain_text",
        "content": "[${branch}] catalog-agent deployed successfully"
      }
    },
    "elements": [
      {
        "tag": "div",
        "fields": [
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Triggered by**\n${username}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Branch**\n${branch}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Job**\n${job}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Service**\n${service_name}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Namespace**\n${namespace}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Image**\n${image}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Commit**\n${commit}"
            }
          },
          {
            "is_short": false,
            "text": {
              "tag": "lark_md",
              "content": "**Full SHA**\n${full_sha}"
            }
          },
          {
            "is_short": false,
            "text": {
              "tag": "lark_md",
              "content": "**Commit message**\n${message}"
            }
          }
        ]
      },
      {
        "tag": "action",
        "actions": [
          {
            "tag": "button",
            "text": {
              "tag": "plain_text",
              "content": "View build"
            },
            "type": "primary",
            "url": "${CIRCLE_BUILD_URL}"
          }
        ]
      }
    ]
  }
}
EOF
}

build_image_push_payload() {
  local color="$1"
  local short_sha="${CIRCLE_SHA1:0:8}"
  local message
  local username
  local branch
  local job
  local image
  local commit
  local full_sha

  message=$(commit_message | escape_json)
  username=$(printf '%s' "$CIRCLE_USERNAME" | escape_json)
  branch=$(printf '%s' "$CIRCLE_BRANCH" | escape_json)
  job=$(printf '%s' "$CIRCLE_JOB" | escape_json)
  image=$(printf '%s' "$IMAGE_REPO:$VERSION_TAG" | escape_json)
  commit=$(printf '%s' "$short_sha" | escape_json)
  full_sha=$(printf '%s' "$CIRCLE_SHA1" | escape_json)

  cat <<EOF
{
  "msg_type": "interactive",
  "card": {
    "config": {
      "wide_screen_mode": true
    },
    "header": {
      "template": "${color}",
      "title": {
        "tag": "plain_text",
        "content": "[${branch}] catalog-agent image pushed successfully"
      }
    },
    "elements": [
      {
        "tag": "div",
        "fields": [
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Triggered by**\n${username}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Branch**\n${branch}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Job**\n${job}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Image**\n${image}"
            }
          },
          {
            "is_short": true,
            "text": {
              "tag": "lark_md",
              "content": "**Commit**\n${commit}"
            }
          },
          {
            "is_short": false,
            "text": {
              "tag": "lark_md",
              "content": "**Full SHA**\n${full_sha}"
            }
          },
          {
            "is_short": false,
            "text": {
              "tag": "lark_md",
              "content": "**Commit message**\n${message}"
            }
          }
        ]
      },
      {
        "tag": "action",
        "actions": [
          {
            "tag": "button",
            "text": {
              "tag": "plain_text",
              "content": "View build"
            },
            "type": "primary",
            "url": "${CIRCLE_BUILD_URL}"
          }
        ]
      }
    ]
  }
}
EOF
}

send_payload() {
  local payload="$1"
  curl -X POST -H "Content-Type: application/json" -d "$payload" "$WEBHOOK_URL" || echo "WARN: Lark notify failed"
}

case "$EVENT" in
  deploy)
    case "$CIRCLE_BRANCH" in
      dev|staging|prod|onprem-dev|onprem-release)
        send_payload "$(build_deploy_payload "$(header_color)")"
        ;;
    esac
    ;;
  image_push)
    case "$CIRCLE_BRANCH" in
      dev|staging|prod|onprem-dev|onprem-release)
        send_payload "$(build_image_push_payload "$(header_color)")"
        ;;
    esac
    ;;
  docker_hub)
    if [[ "$CIRCLE_BRANCH" == "onprem-release" && "$IMAGE_TAG" == "latest" ]]; then
      send_payload "$(build_image_push_payload "$(header_color)")"
    fi
    ;;
  *)
    echo "Unsupported event: $EVENT"
    exit 1
    ;;
esac
