# Selecting Runlevel at boot (good for laptops)

## Garbz

If you are like me than u can't stand waiting for your laptop to bootup because eth0 is trying to be started while the network cable is unplugged.

Likewise you couldn't be bothered starting net.eth0 after every boot if it isn't already set at default.  There had to be a better way.

This is kinda stupid, but u know what they say: "If it's stupid but it works, it's not stupid!"

Basically with the help of an rc init script which is run at the boot runlevel it is possible to select which runlevel to start at boottime by passing cmdline options to the kernel.  (also i've heard this is a bad way to do things, but hey it works.)

Here's how:

Gentoo runs on name based runlevels.  On a default config init starts and begins with the runlevel called "boot".  When boot is completed init moves to runlevel 3 and as per default starts everything in the "default" runlevel.

What i have done is made a script which during "boot" modifies "/etc/runlevels/default" before they are started to selectivly add programs to startup.   The script is nasty, it's badly written (i know nothing about bash this was my first ever attempt and could be MUCH nicer).

So the steps involved:

1. in /etc/runlevels/ are several directories representing the different runlevels for the bootup.  "boot" "default" etc.  each directory contains symbolic links to /etc/init.d/filename to start and stop programs.

Simply add two new folders: "normal" and "offline" (could be different but YOU would need to modify the script).  in these folders use the rc-update command to add things to runlevels:

e.g. 

```
 rc-update add vcron normal

rc-update add net.eth0 normal

rc-update add sshd normal

rc-update add samba normal

rc-update add vcron offline 
```

2.  Take the following script and place it into /etc/init.d/bootlevel

```
#!/sbin/runscript

depend() {

   need localmount

}

start() {

   ebegin "Setting the runlevel according to cmdline args"

   if ! grep "runlevel" /proc/cmdline > /dev/null ;

   then

      eend 2 "Failed sanity check!"

   else

      RUNLEVEL="`cat /proc/cmdline |sed -e 's/.*runlevel=//' |gawk '{print $1}'`"

      if [ $RUNLEVEL = "normal" ] ;

      then

         rm /etc/runlevels/default/*

         cp -d /etc/runlevels/normal/* /etc/runlevels/default

      else 

         if [ $RUNLEVEL = "offline" ] ;

         then

            rm /etc/runlevels/default/*

            cp -d /etc/runlevels/offline/* /etc/runlevels/default

         else

            eend 1 "Failed to interperate runlevel!"

         fi

      fi

   eend $?

   fi

}
```

For thoes that can read it it's kinda obvious and simple what it does, for thoes that can't:

This script reads /proc/cmdline and searches for the runlevel=runlevel command.  it then checks runlevel with an if-then and proceeds to clear the /etc/runlevels/default directory, and then copy the symbolic links from /etc/runlevels/runlevel directory into the default directory.

The end result is when initlevel 3 is started the programs from runlevel not from default are exectuted.

/EDIT:  --------Thanks to bblt for pointing this out:--------

We want the script to start at the boot runlevel (i.e. before runlevel 3 "default" actually starts).  So run this command 

```
rc-update add bootlevel boot
```

3.  The final step is to edit the bootmenu (/etc/grub/menu.lst or grub.conf depending on how it's setup).  and append the desired runlevel to the boot:

```
default 0

timeout 30

splashimage=(hd0,1)/splash.xpm.gz

color dark-gray/black black/light-gray

title=Gentoo Linux 1.4rc5 (Normal)

   root (hd0,1)

   kernel /bzImage root=/dev/hda4 vga=791 video=vesa:1024x768@70 runlevel=normal

   initrd /initrd

title=Gentoo Linux 1.4rc5 (Offline)

   root (hd0,1)

   kernel /bzImage root=/dev/hda4 vga=791 video=vesa:1024x768@70 runlevel=offline

   initrd /initrd

title=Windows XP

   rootnoverify (hd0,0)

   chainloader (hd0,0)+1

title=Gentoo Linux 1.4rc5 (Emergancy)

   root (hd0,1)

   kernel /bzImage root=/dev/hda4 console=tty0 console=ttyS0,115200n8 single
```

There you have it.  Depending which option is selected depends on which directory is copied into "default" and therefore which programs are executed at boot.  No more waiting 15sec for eth0 to timeout when not online.

Any thoughs?  I know this is not the best way to do things.  It there was an easier way let me know,  If you have any sugestions let me know. Otherwise enjoy.

----------

## zhenlin

Nice, but an better way is to have it after the kernel boots, a la Windows 2000, so that people who forget to select the runlevel don't get penalised.

Change

```

if [ -z "${argv1}" ]

then

        if [ -f "${svcdir}/softlevel" ]

        then

                export SOFTLEVEL="$(< ${svcdir}/softlevel)"

        else

                export SOFTLEVEL="boot"

        fi

else

        export SOFTLEVEL="${argv1}"

fi

```

```

if [ -z "${argv1}" ]

then

        if [ -f "${svcdir}/softlevel" ]

        then

                export SOFTLEVEL="$(< ${svcdir}/softlevel)"

        else

                export SOFTLEVEL="boot"

        fi

else

        if [ "${argv1}" = "choose" ]

        then

                # Insert magic here.

                export SOFTLEVEL="${SELECTION}"

        else

                export SOFTLEVEL="${argv1}"

        fi

fi

```

Unfortunately dialog is located in /usr/bin, so we have to resort to some other form of UI. Also, it would be nice if the configuration for the runlevel chooser includes a timeout and a default.

----------

## Garbz

In the current setup the user is not penalised if runlevel is not set, If the runlevel is absent or incorrect nothing is copied and an errror is brought up during boot.  In which case the last settings under default are automatically kept.

----------

## zhenlin

Ah, I misunderstood your code, I thought that it was halting the whole boot process...

----------

## Garbz

 *zhenlin wrote:*   

> Ah, I misunderstood your code

 

 :Very Happy:  That's fine like i said it's poorly written crap that i came up with as a quick fix.

No it just runs at boot time and copies a few files that's it.

----------

## bblt

Excellent! This was just the thing I needed.  It seemed strange to me that Gentoo had no way to specify different runlevels from grub, but this works well.  I wanted to change it a bit so that I could use arbitrary runlevels (in my case, for using bootsplash or not) instead of your hard-coded ones, but I don't really know any bash, so I tried not to change the code that I didn't understand.  Anyway, here's the code for /etc/init.d/bootlevel:

```

#!/sbin/runscript

depend() {

   need localmount

}

start() {

   ebegin "Setting the runlevel according to cmdline args"

   if ! grep "runlevel" /proc/cmdline > /dev/null ;

   then

      RUNLEVEL='normal';

   else

      RUNLEVEL="`cat /proc/cmdline |sed -e 's/.*runlevel=//' |gawk '{print $1}'`"

   fi   

   case /etc/runlevels/{$RUNLEVEL} in

      /etc/runlevels/*)

         rm /etc/runlevels/default/*

         cp -d /etc/runlevels/{$RUNLEVEL}/* /etc/runlevels/default;;

      *)

         eend 1 "Failed to interpret runlevel!";;

   esac

   eend $?

}

```

As long as the value that you use for 'runlevel=' is in the /etc/runlevel directory, it should work ok.

Also, I changed the behavior without any 'runlevel=' option to run the normal level, so if you copy your old default runlevel to normal, 

```

cp -r /etc/runlevels/default /etc/runlevels/normal 

```

all your old grub entries should work without change.

I thought that linking default to the current runlevel might be a nicer way of doing this, but really this works fine as is, and I'm too lazy to try to change it.

----------

## wilburpan

This is really useful information to have, but there is a much easier way of fixing your initial problem:

You can edit the command that sets up your network card in /etc/conf.d/net to adjust the timeout period.  Here's the relevant part of mine:

```
# /etc/conf.d/net:

# For DHCP set iface_eth? to "dhcp"

# For passing options to dhcpcd use dhcpcd_eth?

#

iface_eth0="dhcp"

dhcpcd_eth0="-t 10"

```

The "-t 10" option sets the timeout to 10 seconds.  The default is 60 seconds.  So if my laptop is not hooked up to a network, there's just a 10 second wait and then the boot process continues as usual.  You can of course set -t to whatever you want.

----------

## Garbz

THanks for the info.   But it's not just network card.  There's services i don't need when im not on the network simple as that.

Plus this has countless uses as well.

Also i like the idea of the script, but the point of leaving unchanged if the runlevel option is incorrect or missing, is for safty.   What if the error is that the normal directory is missing ?

Then the program would fail.  I personally think it's safter to in the absence of a specified runlevel to simply boot whatever's in the directory and warn the user.

BTW ur copy of the script didn't work for me.  I'll investigate this further, it may just be my computer but dependancies failed EVERYWHERE.

----------

## Garbz

Ok got it working now.  Stupid file had dos line endings.  Converted to unix and noticed only 1 problem

The {$RUNLEVEL}  should be $RUNLEVEL.  I don't know why, i know in bash the { }  work fine but the script itself failed saying 

can't find /etc/runlevels/{offline}/*

so here's an updated working script.  Thanks for ur input:

```

#!/sbin/runscript

depend() {

      need localmount

}

start() {

      ebegin "Setting the runlevel according to cmdline args"

      if ! grep "runlevel" /proc/cmdline > /dev/null ;

      then

            RUNLEVEL='normal';

      else

            RUNLEVEL="`cat /proc/cmdline |sed -e 's/.*runlevel=//' |gawk '{print $1}'`"

      fi   

      

   case /etc/runlevels/$RUNLEVEL in 

      /etc/runlevels/*)

               rm -f /etc/runlevels/default/*

               cp -d /etc/runlevels/$RUNLEVEL/* /etc/runlevels/default

         ;;

            *)

               eend 1 "Failed to interpret runlevel!"

         ;;

      esac

   

      eend $?

} 

```

Also does anybody know how to write and rcscript like this so that it displays a warning when it aborts rather than an error.  I know eend 0 is sucess.  but i don't necessaraily need a error.

I prefer to set it to abort the script if the runlevel is absent. so rather than

"RUNLEVEL=normal"

have "eend [an error code] "Runlevel not specified, aborted!" "

----------

## bblt

Ahh, thanks for that correction, I had a feeling there might be a problem with my script.  

BTW, I noticed that in your step-by-step instructions, you didn't put down the step: 

```
rc-update add bootlevel boot
```

----------

## Garbz

thanks for that i edited the original post.

----------

## fishhead

I came across this after I wrote a script that lets you do similar things but functions in a slightly diffrent way. I replaced the default runlevel with one that instead presents a dialog that lets you pick the runlevel. 

Here is the script:

```
#!/sbin/runscript

# Copyright 2003 Joshua Goldstein

# Distributed under the terms of the GNU General Public License, v2

# This comes with NO WARRENTY

depend() {

   need localmount

}

start() {

   ebegin "Starting locate"

   

   echo > /tmp/run

    (

 # this is needed to prevent xargs from complaining about the environment being too large and is probably overkill. Its in a subshell, so no harm done.

    unset get_options depinfo_modules depinfo_rsyncd depinfo_distccd get_KV ebegin mark_service_started trace_depend eend depinfo_keymaps schedule_service_startup runlevel_stop depinfo_localmount esyslog stop-daemons  mark_service_stopped needsme iuse depinfo_aumix depinfo_checkfs runlevel_start depinfo_bootmisc depinfo_portmap depinfo_locate depinfo_metalog depinfo_iptables depinfo_domainname depinfo_samba depinfo_nfsmount depinfo_winbind depinfo_netDOTlo depinfo_cupsd depinfo_rmnologin depinfo_xfs depinfo_sshd depinfo_acpid stop-single-daemon depinfo_switch getcols query_before depinfo_netmount wrap_rcscript valid_iafter depinfo_netDOTppp0 depinfo_diald iafter checkserver service_started depinfo_local depinfo_hdparm getpidfile net_service depinfo_urandom depinfo_nscd  depinfo_net depinfo_numlock depinfo_vcron depinfo_netDOTeth0 depinfo_cryptoDASHloop get_options depinfo_modules depinfo_rsyncd depinfo_distccd get_KV ebegin mark_service_started trace_depend eend depinfo_keymaps schedule_service_startup runlevel_stop depinfo_localmount esyslog stop-daemons mark_service_stopped needsme iuse depinfo_aumix depinfo_checkfs runlevel_start usesme depinfo_serial depinfo_checkroot  service_failed depinfo_xdm depinfo_clock depinfo_gkrellmd dependon depinfo_nfs ewarn einfon depinfo_consolefont checkpid query_after list_depend_trace depinfo_powermond mark_service_failed einfo stop_service depinfo_esound depinfo_hostname getcols query_before depinfo_netmount wrap_rcscript valid_iafter depinfo_netDOTppp0 depinfo_diald iafter checkserver service_started depinfo_local  depinfo_hdparm getpidfile net_service depinfo_urandom depinfo_nscd depinfo_net depinfo_numlock depinfo_vcron depinfo_netDOTeth0 depinfo_cryptoDASHloop depinfo_gpm start-single-daemon

    

   echo $dialog_args | sed -e 's/"/\\"/g'  | xargs -P 0 echo --no-cancel --title \"Please select a runlevel\" --radiolist \"These are the available runlevels\" 25 75 20  | xargs -P 0 dialog 2>/tmp/run

   if [[ $? != 0 ]]

   then

      echo $default_level > /tmp/run

   fi

   

   )

   runlevel=`cat /tmp/run`

      

   if [[ ! $runlevel ]] 

   then

      runlevel=$default_level

   fi

   if [[ ! $debug_locate ]]

   then

      maplinks -q /etc/maplinks/$runlevel

      /sbin/rc $runlevel

   else

      echo "I Would run maplinks -q /etc/maplinks/$runlevel"

      echo "I Would run /sbin/rc $runlevel"

   fi

   

   eend 0

}

```

An example configuration:

```
#

# Locate config

#

#dialog_args : arguments to the dialog box, be sure to only quote and have the quotes properly escaped. The runlevel names must be EXACTLY the same as the options here. (i.e. moble means that you _MUST_ have a moble runlevel if you want it to work.)

# a valid example would be...

#dialog_args="home  \"Setup for the house\"  off  moble  \"Moble setup\"  on"

# default_level : the default runlevel

#default_level="moble"

# Set this to only echo, and not actualy change runlevels

#debug_locate="true"

```

The maplinks script needed for the above to work:

```
#!/usr/bin/perl 

# Copyright 2003 Joshua Goldstein

# Distributed under the terms of the GPL v2

# This comes with NO WARRENTY

#

# maplinks - a script that sets up a bunch of links to files

#

# Entry format is tab-delimited: 

# (hardlink|symlink|force-hardlink|force-symlink) link_destination to link_source

sub process_args;

@options = process_args( @ARGV );

# Don't say anything .....

if ( $options[0] eq "quiet" )

{

   close( STDERR );

   open(STDERR,'>','/dev/null');   

}

if (-r $options[1])

{

   open(STDIN,'<',$options[1]) or die("Can't open file");

   $line_num = 1;

   LINE:

   while(<STDIN>)

   {

      my $ln_command = 'ln';

      $line = $_;

      chomp($line);

      @action = split(/\t/,$line);

      

      if($#action != 3) 

      { 

         print STDERR "Invalid line: " . $line_num . "\n";

         $line_num++;

         next LINE; 

      }

      

      # First entry

      SWITCH: 

      {

         if ($action[0] eq "hardlink")       { last SWITCH; }

         if ($action[0] eq "force-hardlink")   { $ln_command .= " -f"; last SWITCH; }

         if ($action[0] eq "symlink")      { $ln_command .= " -s"; last SWITCH; }

         if ($action[0] eq "force-symlink")   { $ln_command .= " -f -s"; last SWITCH; }

         print STDERR "Invalid action, line " . $line_num . "\n"; 

         $line_num++;

         next LINE;

      }

   

      if (-e $action[3])

      {

         $ln_command .= " " . $action[3] . " " . $action[1];

      }

      else

      {

         print STDERR "Source file " . $action[3] . " does not exist\n";

         $line_num++;

         next LINE;

      }

      my $status = system($ln_command);

      

      $line_num++;

   }

}

else { print STDERR "Can't open file!\n"; exit(2); }

exit(0);

sub process_args        #processes the args and returns the input / output files and text flags

{

        sub output_help_message  # add something to compile last modified file

         {

                print(<STDERR>,"usage:\t$0 \[-q\] filename\n");

                exit(0);

         }

        

        my @args = @_;

        my @returnlist = ("not quiet","None");

        for(my $c=0; $c<=$#args; $c++)

         {

                my $p = $args[$c];

                if($p =~ /^(--help|-h)$/)

                 {

                        output_help_message;

                 }

                elsif($p =~ /^-q$/ && $c==0)

                 {

                        $returnlist[0] = "quiet";

                 }

                elsif($c==$#args)

                 {

                        $returnlist[1] = $args[$c];

                 }

                else

                 {

                        print(<STDERR>,"Unknown option or invalid option usage $p\n");

         exit(1);

                 }      

         }       

        return @returnlist;

}

```

Of course, you'll need to rewrite the config files that you use the symlinks on to run in each seperate location, but that is not at all hard. The board seems to not like some of my formating. I have all of these on my website.

----------

## Garbz

That is ... BIG.

I'm not even going to try and actually read that (cause i dont' have time not because i can't).  But i like the menu idea.  I think that would especially usefull for thoes who wish to choose several runlevels, and don't want to fill up the grub menu, and for thoes who are religiously against adding stuff to cmdline args.

----------

## fishhead

Here's a less kludgy solution to the original problem of xargs giving an 'envronment too large' error .... you should probably replace my older script with this ....

```
#!/sbin/runscript

# Copyright 2003 Joshua Goldstein

# Distributed under the terms of the GNU General Public License, v2

# This comes with NO WARRENTY

depend() {

   need localmount

}

start() {

   ebegin "Starting locate"

   

   echo > /tmp/run

   echo $dialog_args | sed -e 's/"/\\"/g'  | env -i xargs -P 0 echo --no-cancel --title \"Please select a runlevel\" --radiolist \"These are the available runlevels\" 25 75 20  | env -i xargs -P 0 dialog 2>/tmp/run

   if [[ $? != 0 ]]

   then

      echo $default_level > /tmp/run

   fi

   runlevel=`cat /tmp/run`

      

   if [[ ! $runlevel ]]

   then

      runlevel=$default_level

   fi

   if [[ ! $debug_locate ]]

   then

      maplinks -q /etc/maplinks/$runlevel

      /sbin/rc $runlevel

   else

      echo "I Would run maplinks -q /etc/maplinks/$runlevel"

      echo "I Would run /sbin/rc $runlevel"

   fi

   

   eend 0

} 

```

----------

## vhkristof

Seems like this ain't necessary anymore with the new 2.6 kernels...

BTW: why not use nonetwork in /etc/runlevels?

----------

## chimy

erm... I got lilo  :Smile:  any ideas for a lilo.conf? Im gonna search the web for stuff like this.

----------

## optilude

I prefer to use my hprofile scripts, which can be found here:

https://forums.gentoo.org/viewtopic.php?t=46180

I think the advantages are:

o It can switch configuration files depending on your hardware profile, not just bootup services. I use this when I'm in VMWare for Windows and want to boot Gentoo to have XF86Config, /etc/conf.d/net and other files automatically find versions appropriate for the current profile. The same might apply to different hardware configurations (e.g. if you're in a docking station, you may want X to default to an external mouse, else it should use your touchpad). This can also be applied to individual users' files in their home directories.

o It can selectively load modules by switching around /etc/modules.autoload.d/kernel-2.6 (or -2.4) for you before the modules are loaded at boot.

o The profile can be determined through a simple script, /etc/hprofile/pdet. You could launch a menu here, check the kernel command line, grep the output of demsg to look for kernel messages giving the profile away, or do anything else that may be appropriate.

It uses the same idea as you - different directories in /etc/runlevels, and a startup script called hprunlevel will select the approriate one - once the profile has been determined, it's all automagic.

NOTE: Read the update to my original hprofile post about critical services and /etc/runlevels/boot/.critical!

Hope other people find it useful!

Martin

----------

## k-dub

I was tempted to hack my startup scripts to allow choosing the runlevel at boot time by reading /proc/cmdline, until I started looking at the startup scripts.

I opened /sbin/rc and noticed it was calling "source /sbin/functions.sh" and later referring to "BOOTLEVEL" and "SOFTLEVEL". This sounded promising, so I opened /sbin/functions.sh and learned that both are set by reading /proc/cmdline. I created a "console" runlevel and added all the same services as my default runlevel except for "xdm". I then rebooted and passed "softlevel=console" at bootup. I was NOT taken to my normal KDM login screen, I was given a login prompt in console mode - IT WORKED!  :Very Happy: 

Use "softlevel=" in your boot loader or pass it in manually and you will reach the desired runlevel, no hacking required.

----------

## petardi

Another solution would be to use ifplugd. It brings up the network interfaces only when the cable is plugged in. It brings them down, when the cable is plugged out.

I don't use different services for online and offline use, so I haven't investigated this further. I guess some fiddling with dependencies should make it possible to bring up other services too.

----------

## zojas

the 'softlevel=foo' thing is awesome.   :Cool: 

but, when I switch to different runlevels, I need different values to be in /etc/conf.d/net; when I'm at home I use eth1 (wireless), when I'm at work I use only eth0 (wired). 

my current solution has 'default' with no networking at all. then after boot I log in as root and run a perl script which adjusts /etc/conf.d/net, adjusts my proxy settings, adjusts my /etc/resolv.conf, and then changes to a different named runlevel. it works, but it would be nicer to just pick a different boot target.

I guess I could write a bash script in /etc/init.d, and set net.ethX to depend on it...I hadn't thought of that before. then I could have a separate script in each runlevel, and use the 'softlevel' at boot time to pick. at other times, all I would have to do would be to run 'rc'

----------

## optilude

 *zojas wrote:*   

> my current solution has 'default' with no networking at all. then after boot I log in as root and run a perl script which adjusts /etc/conf.d/net, adjusts my proxy settings, adjusts my /etc/resolv.conf, and then changes to a different named runlevel. it works, but it would be nicer to just pick a different boot target.

 

This is exactly the kind of problem hprofiles solves. The new version, with multiple profile types, better automatic switching, running of arbitrary scritps when profiles are applied or replaced, and more, can be found at http://hprofile.sourceforge.net.

----------

## k-dub

 *zojas wrote:*   

> when I switch to different runlevels, I need different values to be in /etc/conf.d/net; when I'm at home I use eth1 (wireless), when I'm at work I use only eth0 (wired).

 

You might try Quickswitch http://muthanna.com/quickswitch. 

```
emerge quickswitch
```

It can replace system files with specific versions of them, set ALL your network settings, and even accepts boot-time commands. It's been a great find for me, because I struggled to get my wireless card to work for a long time, now I can switch all my settings in two seconds.  :Smile: 

----------

## optilude

k-dub, how did you find quickswitch integrating with the gentoo boot scripts in /etc/init.d/net.*? I tried it briefly and got frustrated as it seemed to start dhcpcd etc. on its own accord. I also found the configuration file long and confusing (or rather, it seemed to be geared towards RedHat). I've since extended hprofile (http://hprofile.sf.net) to make it more general, and found it easier to set up than quickswitch in Gentoo. (the hprofile tarball comes with my Gentoo init scripts and sample profiles). 

Just wondering how quickswitch stacks up against hprofile. When I used it, I had the feeling I could make it do what hprofile does but that it would be more complicated because quckswitch seems to make assumptions about what it takes to start/stop your network interfaces etc. When using hprofile, I simply rely on the Gentoo init scripts to bring network interfaces up or down (I can switch /etc/conf.d/net around depending on the current profile), which seems safer to me. Or have I got quickswitch wrong?

Martin

----------

## twiggy

Isn't there someway you can make net.eth0 timeout after 5seconds if the cable is not plugged in?

i used dhcpcd -t 5 before when i had slackware on my laptop. can i just edit net.eth0 to do that?   :Shocked: 

----------

## optilude

 *twiggy wrote:*   

> Isn't there someway you can make net.eth0 timeout after 5seconds if the cable is not plugged in?
> 
> i used dhcpcd -t 5 before when i had slackware on my laptop. can i just edit net.eth0 to do that?  

 

The /etc/init.d/net.* scripts read the file /etc/conf.d/net. You can set dhcpcd options here by doing something like 

```
dhcpcd_eth0="-t 5"
```

Martin

----------

## twiggy

 *optilude wrote:*   

>  *twiggy wrote:*   Isn't there someway you can make net.eth0 timeout after 5seconds if the cable is not plugged in?
> 
> i used dhcpcd -t 5 before when i had slackware on my laptop. can i just edit net.eth0 to do that?   
> 
> The /etc/init.d/net.* scripts read the file /etc/conf.d/net. You can set dhcpcd options here by doing something like 
> ...

 

thank you!   :Wink: 

----------

## k-dub

 *optilude wrote:*   

> k-dub, how did you find quickswitch integrating with the gentoo boot scripts in /etc/init.d/net.*? I tried it briefly and got frustrated as it seemed to start dhcpcd etc. on its own accord.

 

I set quickswitch to replace the /etc/conf.d/net file and then restart the service. I had to try a few configurations before I understood what quickswitch was doing and what it was capable of, but I haven't needed to look elsewhere since.

----------

## qeldroma

Another, perhaps easier, way would be, to write a specific initrd-image.

You'ld just have to put some copies of inittab in it, then it can startup via rc-script in the initrd. The inittabs will then be copied over /etc/inittab in the rood-device.

This script includes a timeout for the default runlevel, or keypress for another.

Have no time in the moment to prove, but did similar things before, so it should do like this...

----------

## yamakawa

So uh what is the best? The scripts, quickswitch, or hprofile?

I am just to configure quickswitch after emerging it.

I already set /etc/conf.d/net stuff with dhcp timeout of 5 seconds. This works fine.

The trouble is to select proxy setting. At home I use proxy server of my main PC. At work the laptop is connected directly. To change the proxy setting of like various web browsers is just a pain in my ass!

I think quickswitch can handle this after some hard work.

----------

## zojas

I made a file called /etc/wpad.dat & set all my browsers to use a script to get the location of the proxy. then when I switch runlevels I change out the wpad.dat.

the file should contain code like this:

```

function FindProxyForURL(url, host)

{

  return "PROXY 192.168.0.4:3128; DIRECT";

}

```

that's for my squid proxy at home. at work it's just a different ip address. 

then to set it to no proxy at all the wpad.dat should contain this:

```

function FindProxyForURL(url, host)

{

  return "DIRECT";

}

```

so I do the same old thing of having multiple files in /etc/ and copy the correct one to /etc/wpad.dat when switching runlevels. sometimes I have to close konqueror windows before the change is picked up but at least i don't have to log out.

----------

## optilude

 *yamakawa wrote:*   

> So uh what is the best? The scripts, quickswitch, or hprofile?

 

Well, I'm biased since I wrote hprofile (http://hprofile.sourceforge.net), but I do think that hprofile is quite a simple and elegant solution that gives you a lot of flexibility. Basically, you just provide alternate versions of any file you want switched and name them and place them in a directory that indicates which file to switch and which profile the file represents. You can also write simple scripts that will be run when a profile is applied or unloaded. 

I much prefer this over mangling Gentoo rc scripts or startup code (which will be problematic when new versions of these come out and you have to upgrade, and you could end up unknowingly breaking something). I'm not entirely sure whether quickswitch is more or less powerful (since it takes quite a different approach), but with quickswitch you have to write a long(ish) configuration file and manage the locations of the alternate files yourself. With hprofile, you just place the file in a directory that logically mirrors its destination in the file system and give it a suffix indicating the profile name.

Another advantage is that hprofile comes with sample gentoo init scripts that I am actually using right now, so it's more "gentoo specific". 

There is an ebuild in Bugzilla, but no-one appears to have done anything about it.  :Sad: 

The default install of hprofile is non-destructive (it won't do any damage to your system). I'd recommend you download it and play with it a bit. If you read the FAQ on hprofile.sourceforge.net, that should probably give you all the information you need to get started, and a more detailed manual is found in the README.

Let me know how you get on!

Martin

----------

## k-dub

 *optilude wrote:*   

> I'm not entirely sure whether quickswitch is more or less powerful (since it takes quite a different approach), but with quickswitch you have to write a long(ish) configuration file and manage the locations of the alternate files yourself. With hprofile, you just place the file in a directory that logically mirrors its destination in the file system and give it a suffix indicating the profile name.

 

I haven't tried hprofile, but I feel you have a misconception about quickswitch. I use quickswitch and I have two PCMCIA "schemes" that I want to be able to switch between. My quickswitch config file is about 7 lines and allows me to put my alternate files wherever makes sense to me (to simplify backup scripts, for example). I contributed to this thread to let everyone know how to simply switch runlevels at boot time (softlevel=<runlevelname>). Since quickswitch also has boot time selection, this is how I choose to run.

I'm not saying hprofile is bad, but quickswitch suits me perfectly and I don't feel the need to learn yet another tool. The upside to this thread is letting everyone know all the wonderful options they have abailable.

----------

## yamakawa

Holy smoke! I emerged -p hprofile and only error msg came out.

So I ended up with using quickswitch, which I recently just installed.

The sample script seemed to me quite simple and understandable. I definitely needed this kind of tool for what they call "dynamic file switching" for various setting files. I made two profiles, put the file names of which I wanted to switch.

```
[Home]

dillo=/home/user/.dillo/dillorc.home

emerge=/etc/make.conf.home

[Work]

dillo=/home/user/.dillo/dillorc.work

emerge=/etc/make.conf.work

```

It seemed thus quite simple. However, at that moment, I did not make any copy of the original files, say /etc/make.conf and ~/.dillo/dillorc.

What happneded then was just a crap! When I hit "switchto Home", the original files are overwritten by soft links of the same names with no copies being made to where I directed in the config file! The original files were replaced with links and there were no destination for the links. 

So I ended up with losing my well-maintained make.conf. Screw quickswitch. I should have read your comment earlier  :Crying or Very sad: 

So my big advice to noobs to quickswitch is BACK UP ALL THE FILES YOU WANTED TO SWITCH. Quickswitch does not take care of initial treatment for this. Take good care.

 *optilude wrote:*   

> 
> 
> I'm not entirely sure whether quickswitch is more or less powerful (since it takes quite a different approach), but with quickswitch you have to write a long(ish) configuration file and manage the locations of the alternate files yourself. With hprofile, you just place the file in a directory that logically mirrors its destination in the file system and give it a suffix indicating the profile name.
> 
> Another advantage is that hprofile comes with sample gentoo init scripts that I am actually using right now, so it's more "gentoo specific". 
> ...

 

----------

## optilude

 *Quote:*   

> 
> 
> I haven't tried hprofile, but I feel you have a misconception about quickswitch. I use quickswitch and I have two PCMCIA "schemes" that I want to be able to switch between. My quickswitch config file is about 7 lines and allows me to put my alternate files wherever makes sense to me (to simplify backup scripts, for example). I contributed to this thread to let everyone know how to simply switch runlevels at boot time (softlevel=<runlevelname>). Since quickswitch also has boot time selection, this is how I choose to run. 

 

Well, I know this. But it's still a config file format to read and understand, and there were things I wanted to do with it that I didn't immediately understand. I think the approach of placing files in a directory mirroring the filesystem is much easier to manage than having to manually specify each one, especially when there are more than a handful of files to switch.  I also think the hprofile way of running a single arbitrary script when a profile is applied or unloaded makes more sense than specifying commands from within a central configuration file. But that's just me - this is the beauty of open source!  :Smile: 

Bear in mind that I wrote hprofile before I discovered quickswitch, because hprofile is a general "profile selection" system (and started off being focused on "hardware profiles"). Quickswitch brands itself as specific(ish) to network profiles (although I understand it can go beyond that) so I never even looked at it.

 *yamakawa wrote:*   

> Holy smoke! I emerged -p hprofile and only error msg came out.

 

That's strange. Could you pm me the error? It may be easier to get the tarball from [url]hprofile.sf.net[/url] and just install that - it comes with an install script that puts everything where it should be (and puts binaries in /usr/local/sbin, so it won't mess up portage's well-maintained /usr/sbin), with example profiles and a comprehensive manual in the README. Look at the FAQ on the website first - it should get you up and running quickly so you probably won't have to read the entire README.

 *Quote:*   

> It seemed thus quite simple. However, at that moment, I did not make any copy of the original files, say /etc/make.conf and ~/.dillo/dillorc.
> 
> What happneded then was just a crap! When I hit "switchto Home", the original files are overwritten by soft links of the same names with no copies being made to where I directed in the config file! 
> 
> 

 

Always make backups!  :Smile:  hprofile works on this principle, too (although you can tell it to make copies back and forth if you want, but it makes more sense to use symlinks, because that way if you update a file attached to a profile, your changes are overwritten the next time you apply the same or another profile. hprofile can work around this by copying files back, but it's still a bit risky). However, hprofile will always make a backup of a file before replacing it if that file didn't come from a profile it was managing. 

As an aside, this was very easy to do in hprofile specifically because of the well-defined naming / placement scheme of files - hprofile can easily determine which files came from profiles and which ones did not, and will back files that would've been overwritten up to the profile directory with a ".bak" extension. (It only does this one generation, but it won't overwrite the backup unless it was actually going to replace another file that did *not* come from a profile).

Actually... this stuff is harder to explain than to work with.  :Smile: 

Martin

----------

## yamakawa

 *optilude wrote:*   

> 
> 
>  *yamakawa wrote:*   Holy smoke! I emerged -p hprofile and only error msg came out. 
> 
> That's strange. Could you pm me the error? It may be easier to get the tarball from [url]hprofile.sf.net[/url] and just install that - it comes with an install script that puts everything where it should be (and puts binaries in /usr/local/sbin, so it won't mess up portage's well-maintained /usr/sbin), with example profiles and a comprehensive manual in the README.
> ...

 

Sorry for messing you up with my short message. By this I meant, since I did not even install your ebuild, I got an error telling me that there was no ebuild of that name.

If only there had been the ebuild in my sync tree!

Since you are a hard working maintainer of the source, what do you say to make your ebuild gentoo official?  :Very Happy: 

----------

## optilude

Haha, sorry.  :Smile: 

I made the ebuild, and I want to maintain it, but if I understand how this stuff works, someone responsible for that app-admin part of portage will have to accept it from BugZilla.

For now, you can put it in /usr/local/portage/app-admin, (make sure PORTDIR_OVERLAY is set to /usr/local/portage in /etc/make.conf), run "ebuild /usr/local/portage/app-admin/hprofile/hprofile-2.0_beta2.ebuild digest" and then doing "emerge -p hprofile".

The ebuild does the following:

 - Install hprofile, hprunlevel and hpdet in /usr/sbin

 - Install hprofile startup scripts in /etc/init.d

 - Put hprofile in list of critical startup services in /etc/runlevels/.critical (this is necessary so that hprofile can be started before things like "modules", which are likely to be influenced by the current profile. If you don't like this, or have no use for it, just delete that file - portage will fall back on a sensible default)

 - Put example profiles and settings in /etc/hprofile

 - Put docs in /usr/share/doc/hprofile-2.0_beta2

 - Substitutes a few references in the startup files and configuration files that are necessary because the default hprofile install assumes things are put in /usr/local/sbin, not /usr/sbin

er... think that's it  :Smile: 

Martin

----------

## Zarhan

Is anybody going to integrate this into the main portage tree? I tried it out and it works great.

----------

## BigBaaadBob

 *Zarhan wrote:*   

> Is anybody going to integrate this into the main portage tree? I tried it out and it works great.

 Still not there.   :Crying or Very sad: 

I have another question.  I have four hardware configs for my laptop: No network, in the docking station, using the wired Ethernet, and using the wireless Ethernet.  In addition I have several environments:  Home, work, hotel, etc.  Do any of these tools support the concept of factoring these out so that I can say I want "wired ethernet at the hotel" or "Wireless ethernet at work", without having a setup for every permutation of hardware config and environment?  I'm hoping for N + M configs rather than N * M.

----------

## osti

 *Garbz wrote:*   

> Basically with the help of an rc init script which is run at the boot runlevel it is possible to select which runlevel to start at boottime by passing cmdline options to the kernel.  (also i've heard this is a bad way to do things, but hey it works.)

 

Thanks; I ran into this thread while thinking about the following:

Having (ordered) several raspberry pis for different network tasks, I'd like a "Master SD card" image (Gentoo, of course) pre-configured, dynamically configured during boot based on e.g. the eth0 ethernet address. My first

```
 /etc/init.d/setup-pi
```

 (in runlevel boot) as a reference:

```

#!/sbin/openrc-run

# Copyright 2019 Gentoo Authors

# Distributed under the terms of the GNU General Public License v2

name="setup-pi daemon"

description="based on eth0 ether: set hostname, network config, runlevel configuration"

depend() {

   need localmount

}

start() {

   HW0="dc:a6:32:xx:xx:xx";

   HW1="dc:a6:32:yy:yy:yy";

   HW=$(cat /sys/class/net/eth0/address)

   ebegin "Setting up pi, ether address: $HW"

   ebegin "    hostname"

   case "$HW" in

      $HW0)

      rm /etc/conf.d/hostname && ln -s /etc/conf.d/hostname-rapsi0 /etc/conf.d/hostname ;;

      $HW1)

      rm /etc/conf.d/hostname && ln -s /etc/conf.d/hostname-rapsi1 /etc/conf.d/hostname ;;

      *)

      echo "UNKNOWN ETHERNET ADDRESS"

      false

      ;;

   esac

   eend $?

   ebegin "    network"

   case "$HW" in

      $HW0)

      rm /etc/conf.d/net && ln -s /etc/conf.d/net-rapsi0 /etc/conf.d/net ;;

      $HW1)

      rm /etc/conf.d/net && ln -s /etc/conf.d/net-rapsi1 /etc/conf.d/net ;;

      *)

      echo "UNKNOWN ETHERNET ADDRESS"

      false

      ;;

   esac

   eend $?

   ebegin "    runlevel"

   case "$HW" in

      $HW0)

      rm /etc/runlevels/default && ln -s /etc/runlevels/default-rapsi0 /etc/runlevels/default ;;

      $HW1)

      rm /etc/runlevels/default && ln -s /etc/runlevels/default-rapsi1 /etc/runlevels/default ;;

      *)

      echo "UNKNOWN ETHERNET ADDRESS"

      false

      ;;

   esac

   eend $?

   eend $?

}

```

Still a bit ugly during development / early testing; but it seems to work.

----------

