// set_addr.go
package main

import (
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"flag"
	"fmt"
	"log"
	"time"

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

func main() {
	paddr := flag.String("addr", "", "The mining address (string)")
	pserver := flag.String("server", "", "The db host and port (string)")
	pcoin := flag.String("coin", "", "The coin name (string)")
	puser := flag.String("user", "", "The db user (string)")
	ppassword := flag.String("password", "", "The db user's password (string)")
	pdbn := flag.String("db", "", "The db name (string)")

	flag.Parse()

	if len(*paddr) <= 0 /* || len(*pdb) <= 0 || len(*puser) <= 0 || len(*ppassword) <= 0*/ {
		log.Fatalf("Failed to param")
		return
	}

	addr := *paddr
	user := *puser
	password := *ppassword
	dbserver := *pserver
	coin := *pcoin
	dbn := *pdbn
	if len(user) <= 0 {
		user = "m2pool"
	}
	if len(password) <= 0 {
		password = "pMJzgwrg@Frt8aDXkQAsTGhG!zy!H8Jd"
	}
	if len(dbserver) <= 0 {
		dbserver = "127.0.0.1:3306"
	}
	if len(coin) <= 0 {
		coin = "nexa"
	}
	if len(dbn) <= 0 {
		dbn = "m2pooldb"
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s", user, password, dbserver, dbn)
	//log.Println("dsn", dsn)

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Error opening database: %v", err)
		return
	}
	defer db.Close()

	table_name := coin + "_address"

	var count int
	querySQL := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE addr = ?", table_name)
	err = db.QueryRow(querySQL, addr).Scan(&count)
	if err != nil {
		log.Fatalf("Error checking if address exists: %v", err)
		return
	}

	hash := md5.Sum([]byte(addr + "m2pool_alias"))
	alias := hex.EncodeToString(hash[:])

	if count > 0 {
		updateSQL := fmt.Sprintf("UPDATE %s SET date =?, addr = ?, alias= ?, valid = 1 WHERE addr = ?", table_name)
		_, err := db.Exec(updateSQL, time.Now().Format("2006-01-02 15:04:05"), addr, alias, addr)
		if err != nil {
			log.Fatalf("Error updating address: %v", err)
			return
		}
		fmt.Printf("Address updated: %s\n", addr)
	} else {
		insertSQL := fmt.Sprintf("INSERT INTO %s (date, addr, alias, valid) VALUES (?, ?, ?, ?)", table_name)
		_, err := db.Exec(insertSQL, time.Now().Format("2006-01-02 15:04:05"), addr, alias, 1)
		if err != nil {
			log.Fatalf("Error inserting address: %v", err)
		}
		fmt.Printf("Address inserted: %s\n", addr)
	}
}
