package main

import (
	"flag"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

var help bool
var recurse bool
var force bool
var rf bool

func main() {
	flag.BoolVar(&help, "h", false, "print help")
	flag.BoolVar(&recurse, "r", false, "remove directories and their contents recursively")
	flag.BoolVar(&force, "f", false, "ignore nonexistent files and arguments, never prompt")
	flag.BoolVar(&rf, "rf", false, "-r and -f")
	flag.Parse()
	if help {
		flag.PrintDefaults()
		return
	}
	if rf {
		recurse = true
		force = true
	}
	for _, iv := range flag.Args() {
		list, err := filepath.Glob(iv)
		if err != nil {
			fmt.Println(err.Error())
			if !force {
				return
			}
		}
		for _, jv := range list {
			if recurse {
				err := filepath.Walk(jv, func(path string, info fs.FileInfo, err error) error {
					if err != nil {
						fmt.Println(err.Error())
						if !force {
							return err
						}
					}
					errx := os.Remove(path)
					if errx != nil {
						fmt.Println(errx.Error())
						if !force {
							return errx
						}
					}
					return nil
				})
				if err != nil {
					fmt.Println(err.Error())
					if !force {
						return
					}
				}
			} else {
				err := os.Remove(jv)
				if err != nil {
					fmt.Println(err.Error())
					if !force {
						return
					}
				}
			}
		}
	}
}
