/*
 * Copyright (C) 2015 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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/>.
 *
 */
#include "user-support.h"
#include "config.h"

#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>

#include "../libsnap-confine-private/string-utils.h"
#include "../libsnap-confine-private/utils.h"

void setup_user_data(void) {
    const char *user_data = getenv("SNAP_USER_DATA");

    if (user_data == NULL) return;

    // Only support 'canonicalized' paths.
    if (!sc_is_path_canonical(user_data)) {
        die("user data directory must be an absolute canonical path");
    }

    debug("creating user data directory: %s", user_data);
    if (sc_nonfatal_mkpath(user_data, 0755, -1, -1) < 0) {
        if ((errno == EROFS || errno == EACCES) && !sc_startswith(user_data, "/home/") &&
            !sc_startswith(user_data, "/root/")) {
            // clear errno or it will be displayed in die()
            errno = 0;
            // XXX: may point to the right config option here?
            die("Sorry, home directories outside of /home needs configuration.\n"
                "See https://snapcraft.io/docs/home-outside-home for details.");
        }
        die("cannot create user data directory: %s", user_data);
    };
}
