// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package test

import (
	"context"
	"database/sql"
	"fmt"
	"os"
	"strings"
	"testing"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/stretchr/testify/require"
)

func TestAuditLog(t *testing.T) {
	tidbAddr := os.Getenv("TIDB_ADDR")
	require.NotEmpty(t, tidbAddr, "env 'TIDB_ADDR' is empty")

	auditPath := os.Getenv("AUDIT_PATH")
	require.NotEmpty(t, auditPath, "env 'AUDIT_PATH' is empty")

	_, err := os.Stat(auditPath)
	require.Error(t, err, "audit log file '%s' should not exists when audit not enabled", auditPath)
	if !os.IsNotExist(err) {
		require.NoError(t, err)
	}

	ds := fmt.Sprintf("root@tcp(%s)/test", tidbAddr)
	fmt.Printf("CONNECT: %s\n", ds)
	db, err := sql.Open("mysql", ds)
	require.NoError(t, err)
	defer func() {
		require.NoError(t, db.Close())
	}()

	ctx, cancel := context.WithTimeout(context.TODO(), time.Minute*10)
	defer cancel()
	var conn1 *sql.Conn
	maxRetry := 10
	for i := 0; i <= maxRetry; i++ {
		connCtx, _ := context.WithTimeout(context.TODO(), time.Second)
		conn1, err = db.Conn(connCtx)
		if err != nil {
			fmt.Printf("(%d) connect error: %s\n", i, err.Error())
			time.Sleep(time.Second * 5)
			continue
		}
		break
	}
	require.NoError(t, err)
	fmt.Printf("CONNECT SUCCESS\n")
	defer func() {
		require.NoError(t, conn1.Close())
	}()

	prepareSQLs := []string{
		"admin plugins enable audit",
		`insert into mysql.tidb_audit_table_access (user, db, tbl, access_type) values (".*", ".*", ".*", "")`,
		"flush tidb plugins audit",
	}

	for _, stmt := range prepareSQLs {
		fmt.Printf("EXEC_SQL: %s\n", stmt)
		_, err = conn1.ExecContext(ctx, stmt)
		require.NoError(t, err)
	}

	var content string
	search := "EVENT_CLASS=CONNECTION"
	for i := 0; i <= maxRetry; i++ {
		db2, err := sql.Open("mysql", ds)
		require.NoError(t, err)

		conn2, err := db2.Conn(ctx)
		require.NoError(t, err)
		require.NoError(t, conn2.Close())
		require.NoError(t, db2.Close())
		time.Sleep(time.Second * 2)

		bs, err := os.ReadFile(auditPath)
		if os.IsNotExist(err) {
			fmt.Printf("(%d) '%s' not exists\n", i, auditPath)
			continue
		}

		content = string(bs)
		if !strings.Contains(content, search) {
			fmt.Printf("(%d) search '%s' not found in audit log\n", i, search)
			continue
		}
		break
	}

	require.True(t, strings.Contains(content, search), "'%s' not in log:\n %s", search, content)
}
