// Copyright 2018 The Prometheus Authors
// 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 procfs

import (
	
	
	
	
	
)

var (
	statusLineRE         = regexp.MustCompile(`(\d+) blocks .*\[(\d+)/(\d+)\] \[([U_]+)\]`)
	recoveryLineBlocksRE = regexp.MustCompile(`\((\d+/\d+)\)`)
	recoveryLinePctRE    = regexp.MustCompile(`= (.+)%`)
	recoveryLineFinishRE = regexp.MustCompile(`finish=(.+)min`)
	recoveryLineSpeedRE  = regexp.MustCompile(`speed=(.+)[A-Z]`)
	componentDeviceRE    = regexp.MustCompile(`(.*)\[\d+\]`)
)

// MDStat holds info parsed from /proc/mdstat.
type MDStat struct {
	// Name of the device.
	Name string
	// activity-state of the device.
	ActivityState string
	// Number of active disks.
	DisksActive int64
	// Total number of disks the device requires.
	DisksTotal int64
	// Number of failed disks.
	DisksFailed int64
	// Number of "down" disks. (the _ indicator in the status line)
	DisksDown int64
	// Spare disks in the device.
	DisksSpare int64
	// Number of blocks the device holds.
	BlocksTotal int64
	// Number of blocks on the device that are in sync.
	BlocksSynced int64
	// Number of blocks on the device that need to be synced.
	BlocksToBeSynced int64
	// progress percentage of current sync
	BlocksSyncedPct float64
	// estimated finishing time for current sync (in minutes)
	BlocksSyncedFinishTime float64
	// current sync speed (in Kilobytes/sec)
	BlocksSyncedSpeed float64
	// Name of md component devices
	Devices []string
}

// MDStat parses an mdstat-file (/proc/mdstat) and returns a slice of
// structs containing the relevant info.  More information available here:
// https://raid.wiki.kernel.org/index.php/Mdstat
func ( FS) () ([]MDStat, error) {
	,  := os.ReadFile(.proc.Path("mdstat"))
	if  != nil {
		return nil, 
	}
	,  := parseMDStat()
	if  != nil {
		return nil, fmt.Errorf("%w: Cannot parse %v: %w", ErrFileParse, .proc.Path("mdstat"), )
	}
	return , nil
}

// parseMDStat parses data from mdstat file (/proc/mdstat) and returns a slice of
// structs containing the relevant info.
func parseMDStat( []byte) ([]MDStat, error) {
	 := []MDStat{}
	 := strings.Split(string(), "\n")

	for ,  := range  {
		if strings.TrimSpace() == "" || [0] == ' ' ||
			strings.HasPrefix(, "Personalities") ||
			strings.HasPrefix(, "unused") {
			continue
		}

		 := strings.Fields()
		if len() < 3 {
			return nil, fmt.Errorf("%w: Expected 3+ lines, got %q", ErrFileParse, )
		}
		 := [0] // mdx
		 := [2]  // active or inactive

		if len() <= +3 {
			return nil, fmt.Errorf("%w: Too few lines for md device: %q", ErrFileParse, )
		}

		// Failed disks have the suffix (F) & Spare disks have the suffix (S).
		 := int64(strings.Count(, "(F)"))
		 := int64(strings.Count(, "(S)"))
		, , , ,  := evalStatusLine([], [+1])

		if  != nil {
			return nil, fmt.Errorf("%w: Cannot parse md device lines: %v: %w", ErrFileParse, , )
		}

		 :=  + 2
		if strings.Contains([+2], "bitmap") { // skip bitmap line
			++
		}

		// If device is syncing at the moment, get the number of currently
		// synced bytes, otherwise that number equals the size of the device.
		 := 
		 := 
		 := float64(0)
		 := float64(0)
		 := float64(0)
		 := strings.Contains([], "recovery")
		 := strings.Contains([], "resync")
		 := strings.Contains([], "check")

		// Append recovery and resyncing state info.
		if  ||  ||  {
			if  {
				 = "recovering"
			} else if  {
				 = "checking"
			} else {
				 = "resyncing"
			}

			// Handle case when resync=PENDING or resync=DELAYED.
			if strings.Contains([], "PENDING") ||
				strings.Contains([], "DELAYED") {
				 = 0
			} else {
				, , , , ,  = evalRecoveryLine([])
				if  != nil {
					return nil, fmt.Errorf("%w: Cannot parse sync line in md device: %q: %w", ErrFileParse, , )
				}
			}
		}

		 = append(, MDStat{
			Name:                   ,
			ActivityState:          ,
			DisksActive:            ,
			DisksFailed:            ,
			DisksDown:              ,
			DisksSpare:             ,
			DisksTotal:             ,
			BlocksTotal:            ,
			BlocksSynced:           ,
			BlocksToBeSynced:       ,
			BlocksSyncedPct:        ,
			BlocksSyncedFinishTime: ,
			BlocksSyncedSpeed:      ,
			Devices:                evalComponentDevices(),
		})
	}

	return , nil
}

func evalStatusLine(,  string) (, , ,  int64,  error) {
	 := strings.Fields()
	if len() < 1 {
		return 0, 0, 0, 0, fmt.Errorf("%w: Unexpected statusline %q: %w", ErrFileParse, , )
	}

	 := [0]
	,  = strconv.ParseInt(, 10, 64)
	if  != nil {
		return 0, 0, 0, 0, fmt.Errorf("%w: Unexpected statusline %q: %w", ErrFileParse, , )
	}

	if strings.Contains(, "raid0") || strings.Contains(, "linear") {
		// In the device deviceLine, only disks have a number associated with them in [].
		 = int64(strings.Count(, "["))
		return , , 0, , nil
	}

	if strings.Contains(, "inactive") {
		return 0, 0, 0, , nil
	}

	 := statusLineRE.FindStringSubmatch()
	if len() != 5 {
		return 0, 0, 0, 0, fmt.Errorf("%w: Could not fild all substring matches %s: %w", ErrFileParse, , )
	}

	,  = strconv.ParseInt([2], 10, 64)
	if  != nil {
		return 0, 0, 0, 0, fmt.Errorf("%w: Unexpected statusline %q: %w", ErrFileParse, , )
	}

	,  = strconv.ParseInt([3], 10, 64)
	if  != nil {
		return 0, 0, 0, 0, fmt.Errorf("%w: Unexpected active %d: %w", ErrFileParse, , )
	}
	 = int64(strings.Count([4], "_"))

	return , , , , nil
}

func evalRecoveryLine( string) ( int64,  int64,  float64,  float64,  float64,  error) {
	 := recoveryLineBlocksRE.FindStringSubmatch()
	if len() != 2 {
		return 0, 0, 0, 0, 0, fmt.Errorf("%w: Unexpected recoveryLine blocks %s: %w", ErrFileParse, , )
	}

	 := strings.Split([1], "/")
	,  = strconv.ParseInt([0], 10, 64)
	if  != nil {
		return 0, 0, 0, 0, 0, fmt.Errorf("%w: Unable to parse recovery blocks synced %q: %w", ErrFileParse, [1], )
	}

	,  = strconv.ParseInt([1], 10, 64)
	if  != nil {
		return , 0, 0, 0, 0, fmt.Errorf("%w: Unable to parse recovery to be synced blocks %q: %w", ErrFileParse, [2], )
	}

	// Get percentage complete
	 = recoveryLinePctRE.FindStringSubmatch()
	if len() != 2 {
		return , , 0, 0, 0, fmt.Errorf("%w: Unexpected recoveryLine matching percentage %s", ErrFileParse, )
	}
	,  = strconv.ParseFloat(strings.TrimSpace([1]), 64)
	if  != nil {
		return , , 0, 0, 0, fmt.Errorf("%w: Error parsing float from recoveryLine %q", ErrFileParse, )
	}

	// Get time expected left to complete
	 = recoveryLineFinishRE.FindStringSubmatch()
	if len() != 2 {
		return , , , 0, 0, fmt.Errorf("%w: Unexpected recoveryLine matching est. finish time: %s", ErrFileParse, )
	}
	,  = strconv.ParseFloat([1], 64)
	if  != nil {
		return , , , 0, 0, fmt.Errorf("%w: Unable to parse float from recoveryLine: %q", ErrFileParse, )
	}

	// Get recovery speed
	 = recoveryLineSpeedRE.FindStringSubmatch()
	if len() != 2 {
		return , , , , 0, fmt.Errorf("%w: Unexpected recoveryLine value: %s", ErrFileParse, )
	}
	,  = strconv.ParseFloat([1], 64)
	if  != nil {
		return , , , , 0, fmt.Errorf("%w: Error parsing float from recoveryLine: %q: %w", ErrFileParse, , )
	}

	return , , , , , nil
}

func evalComponentDevices( []string) []string {
	 := make([]string, 0)
	if len() > 3 {
		for ,  := range [4:] {
			 := componentDeviceRE.FindStringSubmatch()
			if  == nil {
				continue
			}
			 = append(, [1])
		}
	}

	return 
}