/* Copyright (C) 2010 TightVNC Team.  All Rights Reserved.
 * Copyright (C) 2014-2017 m-privacy GmbH
 *
 * This 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 2 of the License, or
 * (at your option) any later version.
 * 
 * This software 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 software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 * USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <vncviewer/parameters.h>
#include <os/os.h>

#include <assert.h>
#include <stdio.h>
#include <sys/stat.h>

#ifndef WIN32
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#else
#include <winsock2.h>
#include <windows.h>
#include <wininet.h> /* MinGW needs it */
#include <shlobj.h>
#endif

#if defined(__APPLE__)
#define VNCSUBDIR "/Library/Application Support/TightGate-Viewer/"
#else
#define VNCSUBDIR "/.vnc/"
#endif

int getvnchomedir(char **dirp)
{
  assert(dirp != NULL && *dirp == NULL);

  const char* configuredDir = configDir.getData();
  if (configuredDir) {
    const size_t confDirLen = strlen(configuredDir);
    if (confDirLen) {
      *dirp = new char[confDirLen + 2];
#ifdef WIN32
      sprintf(*dirp, "%s\\", configuredDir);
#else
      sprintf(*dirp, "%s/", configuredDir);
#endif
      return 0;
    }
  }

#ifndef WIN32
  char* homedir = getenv("HOME");
  if (!homedir) {
    const uid_t uid = getuid();
    const struct passwd* passwd = getpwuid(uid);
    if (!passwd) {
      /* Do we want emit error msg here? */
      return -1;
    }
    homedir = passwd->pw_dir;
  }

  const size_t len = strlen(homedir);
  const size_t sublen = strlen(VNCSUBDIR);
  *dirp = new char[len+sublen+1];
  if (!*dirp)
    return -1;

  memcpy(*dirp, homedir, len);
  memcpy(*dirp + len, VNCSUBDIR, sublen);
  (*dirp)[len+sublen] = 0;
#else
  *dirp = new char[MAX_PATH];
  if (!*dirp)
    return -1;

  if (!SHGetSpecialFolderPath(NULL, *dirp, CSIDL_APPDATA, FALSE)) {
    delete[] *dirp;
    return -1;
  }
  memcpy(*dirp+strlen(*dirp), (char*)"\\vnc\\\0", 6);
#endif
  return 0;
}

int fileexists(const char *file)
{
#ifdef WIN32
  return (GetFileAttributes(file) == INVALID_FILE_ATTRIBUTES) ? -1 : 0;
#else
  return access(file, R_OK);
#endif
}


