#!/bin/sh
sed -e '1,/^# C code starts here #/d' "$0" | gcc -x c -static - -o initchroot
strip initchroot
exit "$?"
# C code starts here #
#include <unistd.h>
#include <sys/mount.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
int main()
{
  write(2, "initchroot by x3c33 ( http://ion.nu/ )\n", 39);
  // We probably have to mount /proc first, temporarily
  int ret=mount("proc", "/proc", "proc", 0, 0); // rwflag? 0.. data? 0..
  if(ret){perror("mount");write(2, "mount returned non-zero\n", 24);}
  // Open and read /proc/cmdline
  int cmdfd=open("/proc/cmdline", O_RDONLY);
  printf("cmdfd: %i\n", cmdfd);
  off_t len=2048;
  char buf[len+1];
  len=read(cmdfd, buf, len);
  buf[len]=0;
  printf("cmdline: %s\n", buf);
  close(cmdfd);
  // Unmount /proc
  umount("/proc");
  // Find our new root
  char* dir=strstr(buf, " rootsubdir=");
  if(dir)
  {
    dir+=12;
  }else{
    if(!strncmp(buf, "rootsubdir=", 11)){dir=buf+11;}
  }
  if(dir)
  {
    char* end=strchr(dir, ' ');
    if(!end){end=strchr(dir, '\r');}
    if(!end){end=strchr(dir, '\n');}
    if(end){end[0]=0;}
    ret=chroot(dir);
    if(ret){write(2, "chroot returned non-zero\n", 25);}
    chdir("/");
    // Hack to please Trisquel's mountall ("Sanity check, the root filesystem should be already mounted")
    mount("/", "/", "none", MS_BIND, 0);
  }else{
    write(2, "Didn't find any rootsubdir argument\n", 36);
  }
  printf("dir: %s\n", dir);
  // Pass control to /sbin/init
  char* argv[2]={"/sbin/init", 0};
  execv("/sbin/init", argv);
}
