package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"log"
	"net/smtp"
	"os"
	"path/filepath"
	"strings"

	gomail "github.com/jordan-wright/email"
	"gopkg.in/ini.v1"
)

type Config struct {
	SenderEmail   string
	EmailPassword string
	SMTPServer    string
}

func getConfigFilePath() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	return filepath.Join(dir, "gomail.ini")
}

func readConfig(configFile string) *Config {
	config, err := ini.Load(configFile)
	if err != nil {
		log.Fatalf("Fail to read config file: %v", err)
	}

	return &Config{
		SenderEmail:   config.Section("global").Key("SEND_MAIL").String(),
		EmailPassword: config.Section("global").Key("MAIL_KEY").String(),
		SMTPServer:    config.Section("global").Key("SMTP_SERVER").String(),
	}
}

func createEmail(senderEmail string, recipients []string, subject, text, attachment string) *gomail.Email {
	email := gomail.NewEmail()
	email.From = senderEmail
	email.To = recipients
	email.Subject = subject
	email.Text = []byte(text)

	if attachment != "" {
		email.AttachFile(attachment)
	}

	return email
}

func sendEmail(email *gomail.Email, smtpServer, senderEmail, emailPassword string) error {
	hostSign := strings.Index(smtpServer, ":")
	smtpServerHost := smtpServer[0:(len(smtpServer) - len(smtpServer[hostSign:]))]
	smtpServerPort := smtpServer[hostSign+1:]

	auth := smtp.PlainAuth("", senderEmail, emailPassword, smtpServerHost)

	var err error
	if smtpServerPort != "25" {
		fmt.Println("SSL mode")
		err = email.SendWithTLS(smtpServer, auth, &tls.Config{ServerName: smtpServerHost})
	} else {
		err = email.Send(smtpServer, auth)
	}
	if err != nil {
		log.Fatalf("Failed to send email: %v", err)
	}

	return nil
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}

	if os.IsNotExist(err) {
		return false, nil
	}

	return false, err
}

func main() {
	configFile := getConfigFilePath()
	inifile, _ := PathExists(configFile)
	if !inifile {
		configFile = "/etc/gomail.ini"
	}

	config := readConfig(configFile)

	text := flag.String("t", "", "文本")
	subject := flag.String("s", "", "主题")
	attachment := flag.String("a", "", "添加附件")
	recipients := flag.String("r", "", "接收者邮箱")
	flag.Parse()

	recipientsList := strings.Fields(*recipients)
	fmt.Println("TO =", recipientsList)

	email := createEmail(config.SenderEmail, recipientsList, *subject, *text, *attachment)

	err := sendEmail(email, config.SMTPServer, config.SenderEmail, config.EmailPassword)
	if err != nil {
		log.Fatalf("Failed to send email: %v", err)
	}

	log.Println("send successfully ... ")
}
