// Copyright 2012-2018 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Basename return name with leading path information removed.
//
// Synopsis:
//
//	basename NAME [SUFFIX]
package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
)

var errUsage = errors.New("usage: basename NAME [SUFFIX]")

func run(w io.Writer, args []string) error {
	switch len(args) {
	case 2:
		fileName := filepath.Base(args[0])
		if fileName != args[1] {
			fileName = strings.TrimSuffix(fileName, args[1])
		}
		_, err := fmt.Fprintf(w, "%s\n", fileName)
		return err
	case 1:
		fileName := filepath.Base(args[0])
		_, err := fmt.Fprintf(w, "%s\n", fileName)
		return err
	default:
		return errUsage
	}
}

func main() {
	if err := run(os.Stdout, os.Args[1:]); err != nil {
		log.Fatal(err)
	}
}
