/*
 * 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 <https://www.gnu.org/licenses/>.
 */

#define _GNU_SOURCE 1

#include <sys/types.h>
#include <pwd.h>

#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define PROGNAME "ngcp-chroot-shell"
#define JAILDIR "/home/jail"

static void
fatal(const char *fmt, ...)
{
	va_list args;
	char *errmsg;
	int rc, save_errno = errno;

	va_start(args, fmt);
	rc = vasprintf(&errmsg, fmt, args);
	va_end(args);

	if (rc < 0) {
		fprintf(stderr, "%s: error: cannot print fatal error '%s'\n",
		        PROGNAME, fmt);
		exit(1);
	}

	fprintf(stderr, "%s: error: %s (%s)\n",
	        PROGNAME, errmsg, strerror(save_errno));

	exit(1);
}

int
main(int argc, char *argv[])
{
	struct passwd *pw;
	struct passwd *chroot_pw;
	uid_t uid;
	char *uname;

	errno = 0;

	uid = getuid();
	pw = getpwuid(uid);
	if (pw == NULL)
		fatal("cannot get user name for uid %d", uid);

	if (chdir(pw->pw_dir) < 0)
		fatal("cannot change directory to user home %s", pw->pw_dir);

	if (chroot(JAILDIR) < 0)
		fatal("cannot change root into jail %s", JAILDIR);

	uname = strdup(pw->pw_name);

	chroot_pw = getpwnam(uname);
	if (chroot_pw == NULL)
		fatal("cannot get chroot user name for user %s (%d)", uname, uid);

	if (setenv("HOME", chroot_pw->pw_dir, 1) < 0)
		fatal("cannot set HOME variable for directory in chroot %s",
		      chroot_pw->pw_dir);

	if (chdir(chroot_pw->pw_dir) < 0)
		fatal("cannot change to current directory in chroot %s",
		      chroot_pw->pw_dir);

	if (setuid(chroot_pw->pw_uid) < 0)
		fatal("cannot set user back to original invoker (%s)", uname);

	/* Are we a login shell? */
	if (argv[0][0] == '-') {
		execlp(chroot_pw->pw_shell, chroot_pw->pw_shell, "-l", NULL);
	} else {
		argv[0] = chroot_pw->pw_shell;
		execvp(chroot_pw->pw_shell, argv);
	}
	exit(2);
}
