package ffs

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
	"syscall"
	"time"

	"github.com/mitchellh/go-ps"
	"github.com/pingcap/log"
	"k8s.io/utils/mount"
)

func fuseMount(path string, command string, args []string) (*exec.Cmd, error) {
	cmd := exec.Command(command, args...)
	log.S().Infof("Mounting fuse with command: %s and args: %s", command, args)

	err := cmd.Start()
	if err != nil {
		log.S().Errorf("running ffs mount: %v", err)
		return cmd, fmt.Errorf("Error fuseMount command: %s\nargs: %s\nerror: %v", command, args, err)
	}
	go cmd.Wait()

	return cmd, waitForMount(path, 10*time.Second)
}

func fuseUnmount(path string) (err error) {
	defer func() {
		if !IsNotMountPoint(path) {
			err = waitForUnmount(path, time.Second*10)
		}
	}()
	var process *os.Process
	// as fuse quits immediately, we will try to wait until the process is done
	process, err = findFuseMountProcess(path)
	if err != nil {
		log.S().Errorf("Error getting PID of fuse mount: %s", err)
		return nil
	}
	if process == nil {
		log.S().Warnf("Unable to find PID of fuse mount %s, it must have finished already", path)
		return nil
	}
	log.S().Infof("Found fuse pid %v of mount %s, checking if it still runs", process.Pid, path)
	err = waitForProcess(process, 1)
	if err != nil {
		killProcess(path)
		err = nil
	}
	return
}

func removeVolume(command string, args []string) error {
	log.S().Infof("remove volume with command: %s and args: %s", command, args)
	out, err := exec.Command(command, args...).Output()
	if err != nil {
		log.S().Errorf("failed to remove volume: %s %v", out, err)
		return fmt.Errorf("failed to remove volume: %s %v", out, err)
	}
	return nil
}

func waitForProcess(p *os.Process, backoff int) error {
	if backoff == 3 {
		return fmt.Errorf("Timeout waiting for PID %v to end", p.Pid)
	}
	cmdLine, err := getCmdLine(p.Pid)
	if err != nil {
		log.S().Warnf("Check cmdline of PID %v, assume it is dead", p.Pid)
		return nil
	}
	if cmdLine == "" {
		log.S().Warnf("Fuse process seems dead, returning")
		return nil
	}
	if err := p.Signal(syscall.SIGINT); err != nil {
		log.S().Warnf("Fuse process does not seem active or we are unprivileged: %s", err)
		return nil
	}
	log.S().Infof("Fuse process with PID %v still active, waiting...", p.Pid)
	time.Sleep(time.Duration(backoff*500) * time.Millisecond)
	return waitForProcess(p, backoff+1)
}

func killProcess(path string) {
	var process *os.Process
	process, err := findFuseMountProcess(path)
	if err != nil {
		log.S().Errorf("Error getting PID of fuse mount: %s", err)
		return
	}
	if process == nil {
		log.S().Warnf("Unable to find PID of fuse mount %s, it must have finished already", path)
		return
	}
	log.S().Infof("Found fuse pid %v of mount %s, checking if it still runs", process.Pid, path)
	cmdLine, err := getCmdLine(process.Pid)
	if err != nil {
		log.S().Warnf("Check cmdline of PID %v, assuming it is dead: %s", process.Pid, err)
		return
	}
	if cmdLine == "" {
		log.S().Warnf("Fuse process seems dead, returning")
		return
	}
	if err := process.Signal(syscall.Signal(9)); err != nil {
		log.S().Warnf("Fuse process does not seem active or we are unprivileged: %s", err)
		return
	}
	log.S().Infof("killed process PID %v", process.Pid)
}

func waitForMount(path string, timeout time.Duration) error {
	var elapsed time.Duration
	var interval = 10 * time.Millisecond
	for {
		notMount, err := mount.New("").IsLikelyNotMountPoint(path)
		if err != nil {
			return err
		}
		if !notMount {
			return nil
		}
		time.Sleep(interval)
		elapsed = elapsed + interval
		if elapsed >= timeout {
			return errors.New("Timeout waiting for mount")
		}
	}
}

func waitForUnmount(path string, timeout time.Duration) error {
	var elapsed time.Duration
	var interval = 10 * time.Millisecond
	for {
		if err := mount.New("").Unmount(path); err != nil {
			return err
		}
		time.Sleep(interval)
		notMount := IsNotMountPoint(path)
		if notMount {
			return nil
		}
		elapsed = elapsed + interval
		if elapsed >= timeout {
			return errors.New("Timeout waiting for mount")
		}
	}
}

func findFuseMountProcess(path string) (*os.Process, error) {
	processes, err := ps.Processes()
	if err != nil {
		return nil, err
	}
	for _, p := range processes {
		cmdLine, err := getCmdLine(p.Pid())
		if err != nil {
			log.S().Errorf("Unable to get cmdline of PID %v: %s", p.Pid(), err)
			continue
		}
		if strings.Contains(cmdLine, path) {
			log.S().Infof("Found matching pid %v on path %s", p.Pid(), path)
			return os.FindProcess(p.Pid())
		}
	}
	return nil, nil
}

func getCmdLine(pid int) (string, error) {
	cmdLineFile := fmt.Sprintf("/proc/%v/cmdline", pid)
	cmdLine, err := ioutil.ReadFile(cmdLineFile)
	if err != nil {
		return "", err
	}
	return string(cmdLine), nil
}
