// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

// +build linux freebsd openbsd

package install

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"regexp"
	"time"

	"github.com/keybase/client/go/libkb"
)

// Similar to the Brew install on OSX, the Unix install happens in two steps.
// First, the system package manager installs all the binaries as root. Second,
// an autostart file needs to be written to the user's home dir, so that
// Keybase launches when that user logs in. The second step is done the first
// time the user starts Keybase.
//
// ".desktop" files and the ~/.config/autostart directory are part of the
// freedesktop.org set of standards, which the popular desktop environments
// like Gnome and KDE all support. See
// http://standards.freedesktop.org/desktop-entry-spec/latest/.

const autostartFileText = `# This file is autogenerated when Keybase starts. Keybase will recreate it if you
# delete it, so to disable autostart you should uncomment the line below.

[Desktop Entry]
Name=Keybase
Comment=Keybase Filesystem Service and GUI
Type=Application
Exec=env KEYBASE_START_UI=hideWindow run_keybase

# Uncomment the following line to disable Keybase autostart:
#Hidden=true
`

func autostartDir(context Context) string {
	// strip off the "keybase" folder on the end of the config dir
	return path.Join(context.GetConfigDir(), "..", "autostart")
}

func autostartFilePath(context Context) string {
	return path.Join(autostartDir(context), "keybase_autostart.desktop")
}

// AutoInstall installs auto start on unix
func AutoInstall(context Context, _ string, _ bool, timeout time.Duration, log Log) ( /* newProc */ bool, error) {
	// If the desktop file already exists and has been disabled by the user, short circuit.
	if file, err := os.Open(autostartFilePath(context)); err == nil {
		defer file.Close()
		// Check if the user has disabled autostart manually.
		// If the user inserts Hidden=true, our autostart will be ignored.
		// GNOME inserts X-GNOME-Autostart-enabled=false when startup apps are disabled via gnome-session-properties.
		// In past versions, users have been instructed to disable autostart by commenting out the "Exec" line.
		autostartDisabledRegex := regexp.MustCompile(`(?m)^Hidden=true|^X-GNOME-Autostart-enabled=false|^#\s*Exec`)
		if autostartDisabledRegex.MatchReader(bufio.NewReader(file)) {
			return false, nil
		}
	}

	// If the desktop file doesn't exist or hasn't been disabled by the user, replace it.
	err := os.MkdirAll(autostartDir(context), 0755)
	if err != nil {
		return false, err
	}
	return false, ioutil.WriteFile(autostartFilePath(context), []byte(autostartFileText), 0644)
}

// CheckIfValidLocation is not used on unix
func CheckIfValidLocation() error {
	return nil
}

// KBFSBinPath returns the path to the KBFS executable
func KBFSBinPath(runMode libkb.RunMode, binPath string) (string, error) {
	return kbfsBinPathDefault(runMode, binPath)
}

// kbfsBinName returns the name for the KBFS executable
func kbfsBinName() string {
	return "kbfsfuse"
}

func updaterBinName() (string, error) {
	return "", fmt.Errorf("Updater isn't supported on unix")
}

// RunApp starts the app
func RunApp(context Context, log Log) error {
	// TODO: Start app, see run_keybase: /opt/keybase/Keybase &>> "$logdir/Keybase.app.log"
	return nil
}

func InstallLogPath() (string, error) {
	return "", nil
}

func SystemLogPath() string {
	return ""
}
