#!/bin/bash
if set -o pipefail >/dev/null 2>&1; then
  set -euo pipefail
else
  set -eu
fi

if [ $# -ne 2 ]; then
    echo "Usage: $0 '<base64_encoded_json>' <password>"
    echo "  Arg 1: base64 encoded JSON (without password)"
    echo "  Arg 2: password (required), supports b64: prefix for base64 encoded password"
    echo ""
    echo "  JSON fields:"
    echo "    execute_type : verify | app (required)"
    echo "    verify - 验密, 仅执行login"
    echo "    app    - 应用, 执行login + import_app"
    echo ""
  echo "  verify example: $0 '\$(echo '{\"execute_type\":\"verify\",\"host\":\"\",\"email\":\"\",\"language\":\"\"}' | base64 | tr -d '\\n')' <password>"
  echo "  app example:    $0 '\$(echo '{\"execute_type\":\"app\",\"host\":\"\",\"email\":\"\",\"language\":\"\",\"mode\":\"yaml-content\",\"yaml_content\":\"\"}' | base64 | tr -d '\\n')' <password>"
  echo "  b64 example:    $0 '<base64_json>' 'b64:\$(echo -n '<password>' | base64 | tr -d '\\n')'"
    exit 1
fi

BASE64_PARAM="$1"

if ! command -v jq &>/dev/null; then
    sudo apt-get update -qq && sudo apt-get install -y -qq jq 2>/dev/null ||
        sudo yum install -y -q jq 2>/dev/null
fi

JSON_PARAM=$(echo "$BASE64_PARAM" | base64 -d 2>/dev/null) || {
    echo "{\"errorCode\": 1, \"messageEn\":\"Invalid base64\", \"messageCh\":\"base64解码失败！\"}"
    exit 1
}

if ! echo "$JSON_PARAM" | jq -e '.' >/dev/null 2>&1; then
    echo "{\"errorCode\": 1, \"messageEn\":\"Invalid JSON\", \"messageCh\":\"传入参数json非法！\"}"
    exit 1
fi

EXECUTE_TYPE=$(echo "$JSON_PARAM" | jq -r '.execute_type // empty')
if [ -z "$EXECUTE_TYPE" ]; then
    echo "{\"errorCode\": 1, \"messageEn\":\"Missing execute_type\", \"messageCh\":\"缺少execute_type参数！\"}"
    exit 1
fi

get_local_ip() {
    local ip
    ip=$(ip -4 addr show eth0 2>&1 | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -1)
    if [ -z "$ip" ]; then
        ip=$(hostname -I 2>&1 | awk '{print $1}')
    fi
    if [ -z "$ip" ]; then
        return 1
    fi
    printf '%s' "$ip"
}

HOST=$(echo "$JSON_PARAM" | jq -r '.host // empty')
if [ -z "$HOST" ] || [ "$HOST" = "auto" ]; then
    HOST=$(get_local_ip)
    if [ -z "$HOST" ]; then
        HOST="127.0.0.1"
    fi
fi

BASE_URL="http://${HOST}"

EMAIL=$(echo "$JSON_PARAM" | jq -r '.email // empty')
RAW_PASSWORD="$2"
if [[ "$RAW_PASSWORD" == b64:* ]]; then
    B64_PART="${RAW_PASSWORD#b64:}"
    if [[ ! "$B64_PART" =~ ^[A-Za-z0-9+/=]+$ ]]; then
        echo "{\"errorCode\": 1, \"messageEn\":\"Invalid base64 password\", \"messageCh\":\"b64:前缀后的密码非合法base64编码！\"}"
        exit 1
    fi
    PASSWORD="$B64_PART"
else
    PASSWORD=$(echo -n "$RAW_PASSWORD" | base64 -w0)
fi

if [ -z "$EMAIL" ] || [ -z "$PASSWORD" ]; then
    echo "{\"errorCode\": 1, \"messageEn\":\"Missing email or password\", \"messageCh\":\"缺少email或password参数！\"}"
    exit 1
fi

LANGUAGE=$(echo "$JSON_PARAM" | jq -r '.language // "zh-CN"')

validate_app_params() {
    MODE=$(echo "$JSON_PARAM" | jq -r '.mode // "yaml-content"')
    YAML_CONTENT=$(echo "$JSON_PARAM" | jq -r '.yaml_content // empty')
    if [ -z "$YAML_CONTENT" ]; then
        echo "{\"errorCode\": 1, \"messageEn\":\"Missing yaml_content\", \"messageCh\":\"缺少yaml_content参数！\"}"
        exit 1
    fi
}

COOKIES=""
CSRF_TOKEN=""

login() {
    local response
    response=$(curl -sSL \
        -H 'Accept: */*' \
        -H 'Accept-Language: zh-CN,zh;q=0.9' \
        -H 'Proxy-Connection: keep-alive' \
        -H 'User-Agent: AIAgentLinuxClient' \
        -H 'content-type: application/json' \
        -H 'x-csrf-token;' \
        --data-raw $'{"email":"'"${EMAIL}"'","password":"'"${PASSWORD}"'","language":"'"${LANGUAGE}"'","remember_me":true}' \
        -D - \
        "${BASE_URL}/console/api/login" 2>&1) || true
    local curl_exit=$?

    if [ $curl_exit -ne 0 ] || [ -z "$response" ]; then
        jq -n --arg details "$response" '{"errorCode": 1, "messageEn": "Login failed", "messageCh": "登录失败！", "details": $details}'
        exit 1
    fi

    local headers body
    headers=$(echo "$response" | sed -n '1,/^[ \t]*$/p')
    body=$(echo "$response" | tail -n 1 | tr -d '\r')

    if ! echo "$body" | jq -e '.result == "success"' >/dev/null 2>&1; then
        jq -n --arg details "$body" '{"errorCode": 1, "messageEn": "Login failed", "messageCh": "登录失败！", "details": $details}' >&2
        exit 1
    fi

    COOKIES=$(echo "$headers" | sed -n 's/^Set-Cookie: \([^;]*\);.*/\1/p' | tr '\n' ';' | sed 's/; $//')
    CSRF_TOKEN=$(echo "$COOKIES" | sed -n 's/.*csrf_token=\([^;]*\).*/\1/p')
}

import_app() {
    local csrf_token="$CSRF_TOKEN"

    local data
    data=$(jq -n --arg mode "$MODE" --arg yaml_content "$YAML_CONTENT" '{"mode": $mode, "yaml_content": $yaml_content}')

    local response headers body
    response=$(curl -sSL \
        -H 'Accept: */*' \
        -H 'Accept-Language: zh-CN,zh;q=0.9' \
        -H 'Proxy-Connection: keep-alive' \
        -H 'User-Agent: AIAgentLinuxClient' \
        -H 'content-type: application/json' \
        -H "x-csrf-token: ${csrf_token}" \
        -H "Cookie: ${COOKIES}" \
        --data-raw "$data" \
        -D - \
        "${BASE_URL}/console/api/apps/imports" 2>&1) || true
    local curl_exit=$?

    if [ $curl_exit -ne 0 ] || [ -z "$response" ]; then
        jq -n --arg details "$response" '{"errorCode": 1, "messageEn": "Import failed", "messageCh": "导入失败！", "details": $details}'
        exit 1
    fi

    headers=$(echo "$response" | sed -n '1,/^[ \t]*$/p')
    body=$(echo "$response" | tail -n 1 | tr -d '\r')

    if ! echo "$body" | jq -e '.status == "completed" or .status == "completed-with-warnings"' >/dev/null 2>&1; then
        jq -n --arg details "$body" '{"errorCode": 1, "messageEn": "Import failed", "messageCh": "导入失败！", "details": $details}'
        exit 1
    fi
}

case "$EXECUTE_TYPE" in
    verify)
        login
        echo "{\"errorCode\": 0, \"messageEn\":\"Verify successful\", \"messageCh\":\"验密成功！\"}"
        ;;
    app)
        validate_app_params
        login
        import_app
        echo "{\"errorCode\": 0, \"messageEn\":\"Import successful\", \"messageCh\":\"导入成功！\"}"
        ;;
    *)
        echo "{\"errorCode\": 1, \"messageEn\":\"Invalid execute_type, must be verify or app\", \"messageCh\":\"execute_type非法，必须为verify或app！\"}"
        exit 1
        ;;
esac
