/*
* Naamari-lautta - a wrapper of console cloud clients for Naamari
* Copyright (c) 2015-2017 Sunkware
* Key FP = 6B6D C8E9 3438 6E9C 3D97  56E5 2CE9 A476 99EF 28F6
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* [ WWW: sunkware.org ]                         [ E-MAIL: sunkware@gmail.com ]
 */

package main

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

func Uncloud(cloudClientSyntax *CloudClientSyntax, mountDirPath string, workDirPath string, cryptomenStr string, cryptomenData *CryptomenData) error {
	var err error

	fmt.Println("\n\"" + cryptomenStr + "\": unclouding...")

	if cryptomenData.IsFar == false {
		fmt.Println("Not far.")
		return nil
	}

	if mountDirPath == "" { // use external client
		var command *exec.Cmd

		var clientCmdArgs []string = strings.Split(cloudClientSyntax.RemoveCmd, " ")
		for i := range clientCmdArgs {
			clientCmdArgs[i] = strings.Replace(clientCmdArgs[i], "<<FILENAME>>", cryptomenStr, -1)
		}

		command = exec.Command(cloudClientSyntax.RemoveAppName, clientCmdArgs...)

		command.Stdin = os.Stdin
		command.Stdout = os.Stdout
		command.Stderr = os.Stderr

		fmt.Println(">", strings.Join(command.Args, " "))

		err = command.Run()

		if err != nil {
			return err
		}

	} else { // use system routines for mounted dir
		fmt.Println("Removing \"" + cryptomenStr + "\" from mounted dir...")

		err = os.Remove(mountDirPath + "/" + cryptomenStr)

		if err != nil {
			return err
		}

		fmt.Println("Done.")
	}

	// Looks like the file has been removed from cloud successfully...

	cryptomenData.IsFar = false

	var zeroArray [len(cryptomenData.FarSalt)]byte
	cryptomenData.FarSalt = zeroArray

	cryptomenData.FarTime = 0
	cryptomenData.FarSize = 0

	cryptomenData.Action = ACTION_NONE

	err = WriteCryptomenData(workDirPath+"/."+cryptomenStr, cryptomenData)

	if err != nil {
		return errors.New("cannot write cryptomen")
	}

	return nil
}
