source: client/engine/Boot.lib @ 2fc81c4

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 2fc81c4 was a73649d, checked in by ramon <ramongomez@…>, 11 years ago

#637: Corregidas las condiciones de error incorrectas que no provocaban la salida de una función ante un fallo controlado.

git-svn-id: https://opengnsys.es/svn/branches/version1.0@4187 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 33.4 KB
Line 
1#!/bin/bash
2#/**
3#@file    Boot.lib
4#@brief   Librería o clase Boot
5#@class   Boot
6#@brief   Funciones para arranque y post-configuración de sistemas de archivos.
7#@version 1.0.5
8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
13#         ogBoot int_ndisk int_npartition
14#@brief   Inicia el proceso de arranque de un sistema de archivos.
15#@param   int_ndisk      nº de orden del disco
16#@param   int_npartition nº de orden de la partición
17#@return  (activar el sistema de archivos).
18#@exception OG_ERR_FORMAT    Formato incorrecto.
19#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
20#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
21#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
22#@note    En Linux, debe arrancarse la partición del directorio \c /boot
23#@version 0.1 - Integración para OpenGnSys. - EAC: HDboot; BootLinuxEX en Boot.lib 
24#@author  Antonio J. Doblas Viso, Universidad de Malaga
25#@date    2008-10-27
26#@version 0.9 - Adaptación para OpenGnSys.
27#@author  Ramon Gomez, ETSII Universidad de Sevilla
28#@date    2009-09-11
29#@version 1.0.4 - Soporta modo de arranque Windows (parámetro de inicio "winboot").
30#@author  Ramon Gomez, ETSII Universidad de Sevilla
31#@date    2012-04-12
32#*/ ##
33function ogBoot ()
34{
35# Variables locales.
36local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f
37
38# Si se solicita, mostrar ayuda.
39if [ "$*" == "help" ]; then
40    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
41           "$FUNCNAME 1 1"
42    return
43fi
44# Error si no se reciben 2 parámetros.
45[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
46
47# Detectar tipo de sistema de archivos y montarlo.
48PART=$(ogDiskToDev $1 $2) || return $?
49TYPE=$(ogGetFsType $1 $2) || return $?
50MNTDIR=$(ogMount $1 $2) 2>/dev/null
51# Error si no puede montar sistema de archivos.
52[ -n "$MNTDIR" ] || ogRaiseError OG_ERR_PARTITION "$1, $2" || return $?
53
54case "$TYPE" in
55    EXT[234]|REISERFS|REISER4|JFS|XFS)
56        # Obtiene los parámetros de arranque para Linux.
57        PARAMS=$(ogLinuxBootParameters $1 $2) || return $?
58        read -e KERNEL INITRD APPEND <<<"$PARAMS"
59        # Si no hay kernel, no hay sistema operativo.
60        [ -n "$KERNEL" ] || ogRaiseError $OG_ERR_NOTOS || return $?
61        # Arrancar de partición distinta a la original.
62        [ -e "$MNTDIR/etc" ] && APPEND=$(echo $APPEND | awk -v P="$PART " '{sub (/root=[-+=_/a-zA-Z0-9]* /,"root="P);print}')
63        # Configurar kernel Linux con los parámetros leídos de su GRUB.
64        kexec -l "${MNTDIR}${KERNEL}" --append="$APPEND" --initrd="${MNTDIR}${INITRD}"
65        kexec -e &
66        ;;
67    NTFS|HNTFS|FAT32|HFAT32)
68        # Compruebar si hay un cargador de Windows.
69        for f in io.sys ntldr bootmgr; do
70            FILE="$(ogGetPath $1 $2 $f 2>/dev/null)"
71            [ -n "$FILE" ] && LOADER="$f"
72        done
73        [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS || return $?
74        if [ "$winboot" == "kexec" ]; then
75            # Modo de arranque en caliente (con kexec).
76            cp $OGLIB/grub4dos/* $MNTDIR    # */ (Comentario Doxygen)
77            kexec -l $MNTDIR/grub.exe --append=--config-file="root (hd$[$1-1],$[$2-1]); chainloader (hd$[$1-1],$[$2-1])/$LOADER; tpm --init"
78            kexec -e &
79        else
80            # Modo de arranque por reinicio (con reboot).
81            dd if=/dev/zero of=${MNTDIR}/ogboot.me bs=1024 count=3
82            dd if=/dev/zero of=${MNTDIR}/ogboot.firstboot bs=1024 count=3
83            dd if=/dev/zero of=${MNTDIR}/ogboot.secondboot bs=1024 count=3
84            if  [ -z "$(ogGetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleannboot')" ]; then               
85            ogAddRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot'
86            ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' "cmd /c del c:\ogboot.*"
87            fi
88            # Activar la partición.
89            ogSetPartitionActive $1 $2
90            reboot
91        fi
92        ;;
93    *)  ogRaiseError $OG_ERR_PARTITION "$1, $2"
94        return $?
95        ;;
96esac
97
98# Parar Browser para evitar cuelgues.
99pkill browser
100}
101
102
103#/**
104#         ogGetWindowsName int_ndisk int_npartition
105#@brief   Muestra el nombre del equipo en el registro de Windows.
106#@param   int_ndisk      nº de orden del disco
107#@param   int_npartition nº de orden de la partición
108#@return  str_name - nombre del equipo
109#@exception OG_ERR_FORMAT    Formato incorrecto.
110#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
111#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
112#@version 0.9 - Adaptación para OpenGnSys.
113#@author  Ramon Gomez, ETSII Universidad de Sevilla
114#@date    2009-09-23
115#*/ ##
116function ogGetWindowsName ()
117{
118# Variables locales.
119local PART MNTDIR
120
121# Si se solicita, mostrar ayuda.
122if [ "$*" == "help" ]; then
123    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
124           "$FUNCNAME 1 1  ==>  PRACTICA-PC"
125    return
126fi
127# Error si no se reciben 2 parámetros.
128[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
129
130# Montar el sistema de archivos.
131MNTDIR=$(ogMount $1 $2) 2>/dev/null
132[ -n "$MNTDIR" ] || ogRaiseError OG_ERR_PARTITION "$1, $2" || return $?
133
134# Obtener dato del valor de registro.
135ogGetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName'
136}
137
138
139#/**
140#         ogLinuxBootParameters int_ndisk int_nfilesys
141#@brief   Muestra los parámetros de arranque de un sistema de archivos Linux.
142#@param   int_ndisk      nº de orden del disco
143#@param   int_nfilesys   nº de orden del sistema de archivos
144#@return  str_kernel str_initrd str_parameters ...
145#@exception OG_ERR_FORMAT    Formato incorrecto.
146#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
147#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
148#@warning Función básica usada por \c ogBoot
149#@version 0.9 - Primera adaptación para OpenGnSys.
150#@author  Ramon Gomez, ETSII Universidad de Sevilla
151#@date    2009-09-11
152#@version 0.9.2 - Soporta partición /boot independiente.
153#@author  Ramon Gomez, ETSII Universidad de Sevilla
154#@date    2010-07-20
155#@version 1.0.5 - Mejoras en tratamiento de GRUB2.
156#@author  Ramon Gomez, ETSII Universidad de Sevilla
157#@date    2013-05-14
158#*/ ##
159function ogLinuxBootParameters ()
160{
161# Variables locales.
162local MNTDIR CONFDIR CONFFILE
163
164# Si se solicita, mostrar ayuda.
165if [ "$*" == "help" ]; then
166    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
167           "$FUNCNAME 1 2  ==>  /vmlinuz-3.5.0-21-generic /initrd.img-3.5.0-21-generic root=/dev/sda2 ro splash"
168    return
169fi
170# Error si no se reciben 2 parámetros.
171[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
172
173# Detectar id. de tipo de partición y codificar al mnemonico.
174MNTDIR=$(ogMount $1 $2) 2>/dev/null
175[ -n "$MNTDIR" ] || ogRaiseError OG_ERR_PARTITION "$1, $2" || return $?
176
177# Fichero de configuración de GRUB.
178CONFDIR=$MNTDIR                               # Partición de arranque /boot.
179[ -d $MNTDIR/boot ] && CONFDIR=$MNTDIR/boot   # Partición raíz con directorio boot.
180CONFFILE="$CONFDIR/grubPARTITION/boot/grub/grub.cfg"
181[ ! -e $CONFFILE ] && CONFFILE="$CONFDIR/grub/menu.lst"
182[ ! -e $CONFFILE ] && CONFFILE="$CONFDIR/grub/grub.cfg"
183[ ! -e $CONFFILE ] && CONFFILE="$CONFDIR/grub2/grub.cfg"
184[ -e $CONFFILE ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $?
185
186# Toma del fichero de configuracion los valores del kernel, initrd
187#       y parámetros de arranque usando las cláusulas por defecto
188#       ("default" en GRUB1, "set default" en GRUB2)
189#       y los formatea para que sean compatibles con \c kexec .  */
190# /* (comentario Doxygen)
191awk 'BEGIN {cont=-1;}
192     $1~/^default$/     {sub(/=/," "); def=$2;}
193     $1~/^set$/ && $2~/^default$/ {gsub(/[="]/," "); def=$3;
194                                   if (def ~ /saved_entry/) def=0;
195                                  }
196     $1~/^(title|menuentry)$/ {cont++}
197     $1~/^(kernel|linux)$/ {if (def==cont) {
198                               kern=$2;
199                               sub($1,"");sub($1,"");sub(/^[ \t]*/,"");app=$0}  # /* (comentario Doxygen)
200                           }
201     $1~/^initrd$/      {if (def==cont) init=$2}
202     END {if (kern!="") printf("%s %s %s", kern,init,app)}
203    ' $CONFFILE
204# */ (comentario Doxygen)
205}
206
207
208#/**
209#         ogSetWindowsName int_ndisk int_nfilesys str_name
210#@brief   Establece el nombre del equipo en el registro de Windows.
211#@param   int_ndisk      nº de orden del disco
212#@param   int_nfilesys   nº de orden del sistema de archivos
213#@param   str_name       nombre asignado
214#@return  (nada)
215#@exception OG_ERR_FORMAT     Formato incorrecto.
216#@exception OG_ERR_NOTFOUND   Disco o particion no corresponden con un dispositivo.
217#@exception OG_ERR_PARTITION  Tipo de partición desconocido o no se puede montar.
218#@exception OG_ERR_OUTOFLIMIT Nombre Netbios con más de 15 caracteres.
219#@version 0.9 - Adaptación a OpenGnSys.
220#@author  Ramon Gomez, ETSII Universidad de Sevilla
221#@date    2009-09-24
222#@version 1.0.5 - Establecer restricción de tamaño de nombre Netbios.
223#@author  Ramon Gomez, ETSII Universidad de Sevilla
224#@date    2013-03-20
225#*/ ##
226function ogSetWindowsName ()
227{
228# Variables locales.
229local PART MNTDIR NAME
230
231# Si se solicita, mostrar ayuda.
232if [ "$*" == "help" ]; then
233    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_name" \
234           "$FUNCNAME 1 1 PRACTICA-PC"
235    return
236fi
237# Error si no se reciben 3 parámetros.
238[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
239# Error si el nombre supera los 15 caracteres.
240[ ${#3} -le 15 ] || ogRaiseError $OG_ERR_OUTOFLIMIT "\"${3:0:15}...\"" || return $?
241
242# Montar el sistema de archivos.
243MNTDIR=$(ogMount $1 $2) 2>/dev/null
244[ -n "$MNTDIR" ] || ogRaiseError OG_ERR_PARTITION "$1, $2" || return $?
245NAME="$3"
246
247# Modificar datos de los valores de registro.
248ogSetRegistryValue $MNTDIR system '\ControlSet001\Control\ComputerName\ComputerName\ComputerName' "$NAME" 2>/dev/null
249ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
250ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\Hostname' "$NAME" 2>/dev/null
251ogSetRegistryValue $MNTDIR system '\ControlSet001\Services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
252ogSetRegistryValue $MNTDIR system '\ControlSet001\services\Tcpip\Parameters\NV Hostname' "$NAME" 2>/dev/null
253}
254
255
256#/**
257#         ogSetWinlogonUser int_ndisk int_npartition str_username
258#@brief   Establece el nombre de usuario por defecto en la entrada de Windows.
259#@param   int_ndisk      nº de orden del disco
260#@param   int_npartition nº de orden de la partición
261#@param   str_username   nombre de usuario por defecto
262#@return  (nada)
263#@exception OG_ERR_FORMAT    Formato incorrecto.
264#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
265#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
266#@version 0.9.2 - Adaptación a OpenGnSys.
267#@author  Ramon Gomez, ETSII Universidad de Sevilla
268#@date    2010-07-20
269#*/ ##
270function ogSetWinlogonUser ()
271{
272# Variables locales.
273local PART MNTDIR NAME
274
275# Si se solicita, mostrar ayuda.
276if [ "$*" == "help" ]; then
277    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition str_username" \
278           "$FUNCNAME 1 1 USUARIO"
279    return
280fi
281# Error si no se reciben 3 parámetros.
282[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $?
283
284# Montar el sistema de archivos.
285MNTDIR=$(ogMount $1 $2) 2>/dev/null
286[ -n "$MNTDIR" ] || ogRaiseError OG_ERR_PARTITION "$1, $2" || return $?
287NAME="$3"
288
289# Modificar datos en el registro.
290ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' "$3"
291}
292
293
294#/**
295#         ogBootMbrXP int_ndisk
296#@brief   Genera un nuevo Master Boot Record en el disco duro indicado, compatible con los SO tipo Windows
297#@param   int_ndisk      nº de orden del disco
298#@return  salida del programa my-sys
299#@exception OG_ERR_FORMAT    Formato incorrecto.
300#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
301#@version 0.9 - Adaptación a OpenGnSys.
302#@author  Antonio J. Doblas Viso. Universidad de Málaga
303#@date    2009-09-24
304#*/ ##
305
306function ogBootMbrXP ()
307{
308# Variables locales.
309local DISK
310
311# Si se solicita, mostrar ayuda.
312if [ "$*" == "help" ]; then
313    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
314           "$FUNCNAME 1"
315    return
316fi
317# Error si no se recibe 1 parámetro.
318[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
319
320DISK="$(ogDiskToDev $1)" || return $?
321ms-sys -z -f $DISK
322ms-sys -m -f $DISK
323}
324
325
326#/**
327#         ogBootMbrGeneric int_ndisk
328#@brief   Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux.
329#@param   int_ndisk      nº de orden del disco
330#@return  salida del programa my-sys
331#@exception OG_ERR_FORMAT    Formato incorrecto.
332#@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar.
333#@version 0.9 - Adaptación a OpenGnSys.
334#@author  Antonio J. Doblas Viso. Universidad de Málaga
335#@date    2009-09-24
336#*/ ##
337
338function ogBootMbrGeneric ()
339{
340# Variables locales.
341local DISK
342
343# Si se solicita, mostrar ayuda.
344if [ "$*" == "help" ]; then
345    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk " \
346           "$FUNCNAME 1 "
347    return
348fi
349# Error si no se recibe 1 parámetro.
350[ $# == 1 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
351
352DISK="$(ogDiskToDev $1)" || return $?
353ms-sys -z -f $DISK
354ms-sys -s -f $DISK
355}
356
357
358
359
360#/**
361#         ogFixBootSector int_ndisk int_parition
362#@brief   Corrige el boot sector de una particion activa para MS windows/dos -fat-ntfs
363#@param   int_ndisk      nº de orden del disco
364#@param   int_partition     nº de particion
365#@return 
366#@exception OG_ERR_FORMAT    Formato incorrecto.
367#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
368#@version 0.9 - Adaptación a OpenGnSys.
369#@author  Antonio J. Doblas Viso. Universidad de Málaga
370#@date    2009-09-24
371#*/ ##
372
373function ogFixBootSector ()
374{
375# Variables locales.
376local PARTYPE DISK PART FILE
377
378# Si se solicita, mostrar ayuda.
379if [ "$*" == "help" ]; then
380    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
381           "$FUNCNAME 1 1 "
382    return
383fi
384
385# Error si no se reciben 2 parámetros.
386[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
387
388#TODO, solo si la particion existe
389#TODO, solo si es ntfs o fat
390PARTYPE=$(ogGetPartitionId $1 $2)
391case "$PARTYPE" in
392        1|4|6|7|b|c|e|f|17|700)
393        ;;
394        *)
395        return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
396        ;;
397esac
398
399ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
400
401#Preparando instruccion
402let DISK=$1-1   
403PART=$2
404FILE=/tmp/temp$$
405cat > $FILE <<EOF
406disk=$DISK
407main_part=$PART
408fix_first_sector=yes
409EOF
410
411spartlnx.run -cui -nm -a -f $FILE &
412sleep 5
413ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
414rm -f $FILE
415}
416
417
418
419#/**
420#         ogWindowsBootParameters int_ndisk int_parition
421#@brief   Configura el gestor de arranque de windows 7 / vista / XP / 2000
422#@param   int_ndisk      nº de orden del disco
423#@param   int_partition     nº de particion
424#@return 
425#@exception OG_ERR_FORMAT    Formato incorrecto.
426#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
427#@version 0.9 - Integración desde EAC para OpenGnSys.
428#@author  Antonio J. Doblas Viso. Universidad de Málaga
429#@date    2009-09-24
430#@version 1.0.1 - Adapatacion para OpenGnsys.
431#@author  Antonio J. Doblas Viso. Universidad de Málaga
432#@date    2011-05-20
433#@version 1.0.5 - Soporte para Windows 8 y Windows 8.1.
434#@author  Ramon Gomez, ETSII Universidad de Sevilla
435#@date    2014-01-28
436#*/ ##
437
438function ogWindowsBootParameters ()
439{
440# Variables locales.
441local PART DISK FILE VERSION WINVER MOUNT
442
443# Si se solicita, mostrar ayuda.
444if [ "$*" == "help" ]; then
445    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partition " \
446           "$FUNCNAME 1 1 "
447    return
448fi
449
450# Error si no se reciben 2 parámetros.
451[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
452
453ogDiskToDev $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
454
455#Preparando variables adaptadas a sintaxis windows.
456let DISK=$1-1
457PART=$2
458FILE=/tmp/temp$$
459
460VERSION=$(ogGetOsVersion $1 $2)
461
462if echo "$VERSION" | grep "Windows 8.1"
463then
464        WINVER="Windows 8.1"
465elif echo "$VERSION" | grep "Windows 8"
466then
467        WINVER="Windows 8"
468elif echo "$VERSION" | grep "Windows 7"
469then
470        WINVER="Windows 7"
471elif echo "$VERSION" | grep "Windows Seven"
472then
473        WINVER="Windows Vista"
474elif echo "$VERSION" | grep "XP"
475then
476        MOUNT=$(ogMount $1 $2)
477        [ -f ${MOUNT}/boot.ini ] || return $(ogRaiseError $OG_ERR_NOTOS; echo $?)
478        cat ${MOUNT}/boot.ini | sed s/partition\([0-9]\)/partition\($PART\)/g | sed s/rdisk\([0-9]\)/rdisk\($DISK\)/g > ${MOUNT}/tmp.boot.ini; mv ${MOUNT}/tmp.boot.ini ${MOUNT}/boot.ini
479        return 0
480else
481        return $(ogRaiseError $OG_ERR_NOTOS; echo $?)
482fi
483
484ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?)
485
486
487#Preparando instruccion Windows Resume Application
488cat > $FILE <<EOF
489boot_disk=$DISK
490boot_main_part=$PART
491disk=$DISK
492main_part=$PART
493boot_entry=Windows Resume Application
494EOF
495spartlnx.run -cui -nm -w -f $FILE &
496sleep 5
497ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
498
499 
500
501#Preparando instruccion tipo windows
502cat > $FILE <<EOF
503boot_disk=$DISK
504boot_main_part=$PART
505disk=$DISK
506main_part=$PART
507boot_entry=$WINVER
508EOF
509spartlnx.run -cui -nm -w -f $FILE &
510sleep 5
511ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
512
513
514##Preparando instruccion        Ramdisk Options
515cat > $FILE <<EOF
516boot_disk=$DISK
517boot_main_part=$PART
518disk=$DISK
519main_part=$PART
520boot_entry=Ramdisk Options
521EOF
522spartlnx.run -cui -nm -w -f $FILE &
523sleep 5
524ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
525
526
527#Preparando instruccion Windows Boot Manager
528cat > $FILE <<EOF
529boot_disk=$DISK
530boot_main_part=$PART
531disk=$DISK
532main_part=$PART
533boot_entry=Windows Boot Manager
534EOF
535spartlnx.run -cui -nm -w -f $FILE &
536sleep 5
537ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
538
539
540#Preparando instruccion Herramienta de diagnóstico de memoria de Windows
541cat > $FILE <<EOF
542boot_disk=$DISK
543boot_main_part=$PART
544disk=$DISK
545main_part=$PART
546boot_entry=Herramienta de diagnóstico de memoria de Windows
547EOF
548spartlnx.run -cui -nm -w -f $FILE &
549sleep 5
550ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
551
552}
553
554
555#         ogWindowsRegisterPartition int_ndisk int_partiton str_volume int_disk int_partition
556#@brief   Registra una partición en windows con un determinado volumen.
557#@param   int_ndisk      nº de orden del disco a registrar
558#@param   int_partition     nº de particion a registrar
559#@param   str_volumen      volumen a resgistar
560#@param   int_ndisk_windows      nº de orden del disco donde esta windows
561#@param   int_partition_windows     nº de particion donde esta windows
562#@return 
563#@exception OG_ERR_FORMAT    Formato incorrecto.
564#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
565#@version 0.9 - Adaptación a OpenGnSys.
566#@author  Antonio J. Doblas Viso. Universidad de Málaga
567#@date    2009-09-24
568#*/ ##
569function ogWindowsRegisterPartition ()
570{
571# Variables locales.
572local PART DISK FILE REGISTREDDISK REGISTREDPART REGISTREDVOL VERSION SYSTEMROOT
573
574# Si se solicita, mostrar ayuda.
575if [ "$*" == "help" ]; then
576    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk_TO_registre int_partition_TO_registre str_NewVolume int_disk int_parition " \
577           "$FUNCNAME 1 1 c: 1 1"
578    return
579fi
580
581# Error si no se reciben 5 parámetros.
582[ $# == 5 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
583
584REGISTREDDISK=$1
585REGISTREDPART=$2
586REGISTREDVOL=$(echo $3 | cut -c1 | tr '[:lower:]' '[:upper:]')
587DISK=$4
588PART=$5
589FILE=/tmp/temp$$
590
591ogDiskToDev $REGISTREDDISK $REGISTREDPART || return $(ogRaiseError $OG_ERR_PARTITION "particion a registrar "; echo $?)
592ogDiskToDev $DISK $PART || return $(ogRaiseError $OG_ERR_PARTITION "particion de windows"; echo $?)
593
594ogGetOsType $DISK $PART | grep "Windows" || return $(ogRaiseError $OG_ERR_NOTOS "no es windows"; echo $?)
595
596VERSION=$(ogGetOsVersion $DISK $PART)
597
598#Systemroot
599
600if ogGetPath $DISK $PART WINDOWS
601then
602        SYSTEMROOT="Windows"
603elif ogGetPath $DISK $PART WINNT
604then
605        SYSTEMROOT="winnt"
606else
607        return $(ogRaiseError $OG_ERR_NOTOS; echo $?)
608fi
609
610ogUnmount $DISK $PART
611let DISK=$DISK-1
612let REGISTREDDISK=$REGISTREDDISK-1
613#Preparando instruccion Windows Boot Manager
614cat > $FILE <<EOF
615windows_disk=$DISK
616windows_main_part=$PART
617windows_dir=$SYSTEMROOT
618disk=$REGISTREDDISK
619main_part=$REGISTREDPART
620;ext_part
621part_letter=$REGISTREDVOL
622EOF
623spartlnx.run -cui -nm -u -f $FILE &
624sleep 5
625ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null
626
627}
628
629
630#         ogGrubInstallMbr  int_disk_GRUBCFG  int_partition_GRUBCFG #@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
631#@brief   Instala y actualiza el gestor grub el el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows.
632#@param   int_disk_SecondStage     
633#@param   int_part_SecondStage     
634#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
635#@return 
636#@exception OG_ERR_FORMAT    Formato incorrecto.
637#@version 1.0.2 - Primeras pruebas.
638#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
639#@date    2011-10-29
640#@version 1.0.3 - Soporte para linux de 32 y 64 bits
641#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
642#@date    2012-03-13
643#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la primera etapa
644#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
645#@date    2012-03-13
646#*/ ##
647
648function ogGrubInstallMbr {
649
650# Variables locales.
651local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
652
653# Si se solicita, mostrar ayuda.
654if [ "$*" == "help" ]; then
655    ogHelp "$FUNCNAME" "$FUNCNAME  int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \"  " \
656           "$FUNCNAME 1 1 FALSE " \
657           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
658    return
659fi 
660
661# Error si no se reciben 2 parámetros.
662[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
663
664
665DISK=$1; PART=$2;
666CHECKOS=${3:-"FALSE"}
667KERNELPARAM=$4
668BACKUPNAME=".backup.og"
669
670#Error si no es linux.
671#TODO: comprobar si se puede utilizar la particion windows como contenedor de grub.
672#VERSION=$(ogGetOsVersion $DISK $PART)
673#echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
674
675#Localizar primera etapa del grub
676FIRSTSTAGE=$(ogDiskToDev $DISK)
677
678#localizar disco segunda etapa del grub
679SECONDSTAGE=$(ogMount $DISK $PART)
680
681# prepara el directorio principal de la segunda etapa
682[ -d ${SECONDSTAGE}/boot/grub/ ]  || mkdir -p ${SECONDSTAGE}/boot/grub/
683
684#Localizar directorio segunda etapa del grub   
685PREFIXSECONDSTAGE="/boot/grubMBR"
686
687# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
688if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
689then
690    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
691    then
692        # Si no se reconfigura se utiliza el grub.cfg orginal
693        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
694                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
695        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
696        # Reactivamos el grub con el grub.cfg original.
697        grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
698        return $?
699    fi
700fi
701
702# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
703#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
704echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
705echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
706
707#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup
708[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
709
710#Preparar configuración segunda etapa: crear ubicacion
711mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
712#Preparar configuración segunda etapa: crear cabecera del fichero
713/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
714#Preparar configuración segunda etapa: crear entrada del sistema operativo
715grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
716
717#Instalar el grub
718grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
719}
720
721
722
723#         ogGrubInstallPartition int_disk_SECONDSTAGE  int_partition_SECONDSTAGE bolean_Check_Os_installed_and_Configure_2ndStage
724#@brief   Instala y actualiza el gestor grub en el bootsector de la particion indicada
725#@param   int_disk_SecondStage     
726#@param   int_part_SecondStage     
727#@param   bolean_Check_Os_installed_and_Configure_2ndStage   true | false[default]
728#@param   str "kernel param "   
729#@return 
730#@exception OG_ERR_FORMAT    Formato incorrecto.
731#@version 1.0.2 - Primeras pruebas.
732#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
733#@date    2011-10-29
734#@version 1.0.3 - Soporte para linux de 32 y 64 bits
735#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
736#@date    2012-03-13
737#@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la priemra etapa
738#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
739#@date    2012-03-13
740#*/ ##
741
742function ogGrubInstallPartition {
743
744# Variables locales.
745local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME
746
747# Si se solicita, mostrar ayuda.
748if [ "$*" == "help" ]; then
749    ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage   \"param param \" " \
750           "$FUNCNAME 1 1 FALSE " \
751           "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" "
752    return
753fi 
754
755# Error si no se reciben 2 parámetros.
756[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?)
757
758DISK=$1; PART=$2;
759CHECKOS=${3:-"FALSE"}
760KERNELPARAM=$4
761BACKUPNAME=".backup.og"
762
763#error si no es linux.
764VERSION=$(ogGetOsVersion $DISK $PART)
765echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?)
766
767#Localizar primera etapa del grub
768FIRSTSTAGE=$(ogDiskToDev $DISK $PART)
769
770#localizar disco segunda etapa del grub
771SECONDSTAGE=$(ogMount $DISK $PART)
772
773#Localizar directorio segunda etapa del grub   
774PREFIXSECONDSTAGE="/boot/grubPARTITION"
775
776# Si Reconfigurar segunda etapa (grub.cfg) == FALSE
777if [ -f ${SECONDSTAGE}/boot/grub/grub.cfg -o -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ]
778then
779    if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ]
780    then
781        # Si no se reconfigura se utiliza el grub.cfg orginal
782        [ -f ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME ${SECONDSTAGE}/boot/grub/grub.cfg
783                # Si no se reconfigure se borra los ficheros previos de configuración específicos de opengnsys.
784        [ -d ${SECONDSTAGE}${PREFIXSECONDSTAGE} ] &&  rm -fr ${SECONDSTAGE}${PREFIXSECONDSTAGE}
785        # Reactivamos el grub con el grub.cfg original.
786        grub-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE
787        return $?
788    fi
789fi
790
791# SI Reconfigurar segunda etapa (grub.cfg) == TRUE
792#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive
793echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub
794echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub
795
796#Evitar detectar modo recovery - mover grub.cfg original a grub.cfg.backup.og
797[ -f ${SECONDSTAGE}/boot/grub/grub.cfg ] && mv ${SECONDSTAGE}/boot/grub/grub.cfg ${SECONDSTAGE}/boot/grub/grub.cfg$BACKUPNAME
798
799#Preparar configuración segunda etapa: crear ubicacion
800mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/
801#Preparar configuración segunda etapa: crear cabecera del fichero
802/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
803#Preparar configuración segunda etapa: crear entrada del sistema operativo
804grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg
805
806#Instalar el grub
807grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTSTAGE
808}
809
810###
811#En pruebas
812##
813#/**
814#         ogConfigureFstab int_ndisk int_nfilesys
815#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
816#@param   int_ndisk      nº de orden del disco
817#@param   int_nfilesys   nº de orden del sistema de archivos
818#@return  (nada)
819#@exception OG_ERR_FORMAT    Formato incorrecto.
820#@exception OG_ERR_NOTFOUND  No se encuentra el fichero fstab a procesar.
821#@warning Puede haber un error si hay más de 1 partición swap.
822#@version 1.0.5 - Primera versión para OpenGnSys.
823#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
824#@date    2013-03-21
825#*/ ##
826function ogConfigureFstab {
827# Variables locales.
828local FSTAB DEFROOT PARTROOT DEFSWAP PARTSWAP
829
830# Si se solicita, mostrar ayuda.
831if [ "$*" == "help" ]; then
832    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
833           "$FUNCNAME 1 1"
834    return
835fi
836# Error si no se reciben 2 parámetros.
837[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
838# Error si no se encuentra un fichero  etc/fstab  en el sistema de archivos.
839FSTAB=$(ogGetPath $1 $2 /etc/fstab) 2>/dev/null
840[ -n "$FSTAB" ] || ogRaiseError $OG_ERR_NOTFOUND "$1,$2,/etc/fstab" || return $?
841
842# Hacer copia de seguridad del fichero fstab original.
843cp -a ${FSTAB} ${FSTAB}.backup
844# Dispositivo del raíz en fichero fstab: 1er campo (si no tiene "#") con 2º campo = "/".
845DEFROOT=$(awk '$1!~/#/ && $2=="/" {print $1}' ${FSTAB})
846PARTROOT=$(ogDiskToDev $1 $2)
847# Configuración de swap (solo 1ª partición detectada).
848PARTSWAP=$(blkid -t TYPE=swap | awk -F: 'NR==1 {print $1}')
849if [ -n "$PARTSWAP" ]
850then
851    # Dispositivo de swap en fichero fstab: 1er campo (si no tiene "#") con 3er campo = "swap".
852    DEFSWAP=$(awk '$1!~/#/ && $3=="swap" {print $1}' ${FSTAB})
853    if [ -n "$DEFSWAP" ]
854    then
855        echo "Hay definicion de swap en el fstab $DEFSWAP -> modificamos fichero con nuevo valor $DEFSWAP->$PARTSWAP"   # Mensaje temporal.
856        sed "s|$DEFSWAP|$PARTSWAP|g ; s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
857    else
858        echo "No hay definicion de swap y si hay partición swap -> moficamos fichero"   # Mensaje temporal.
859        sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
860        echo "$PARTSWAP  none    swap    sw   0  0" >> ${FSTAB}
861    fi 
862else
863    echo "No hay partición swap -> configuramos fstba"  # Mensaje temporal.
864    sed "s|$DEFROOT|$PARTROOT|g" ${FSTAB}.backup > ${FSTAB}
865fi
866}
867
868
869###
870#En pruebas
871##
872#/**
873#         ogSetLinuxName int_ndisk int_nfilesys [str_name]
874#@brief   Establece el nombre del equipo en los ficheros hostname y hosts.
875#@param   int_ndisk      nº de orden del disco
876#@param   int_nfilesys   nº de orden del sistema de archivos
877#@param   str_name       nombre asignado (opcional)
878#@return  (nada)
879#@exception OG_ERR_FORMAT    Formato incorrecto.
880#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
881#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
882#@note    Si no se indica nombre, se asigna un valor por defecto.
883#@version 1.0.5 - Primera versión para OpenGnSys.
884#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
885#@date    2013-03-21
886#*/ ##
887function ogSetLinuxName ()
888{
889# Variables locales.
890local MNTDIR ETC NAME
891
892# Si se solicita, mostrar ayuda.
893if [ "$*" == "help" ]; then
894    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_name]" \
895           "$FUNCNAME 1 1" "$FUNCNAME 1 1 practica-pc"
896    return
897fi
898# Error si no se reciben 2 o 3 parámetros.
899case $# in
900    2)   # Asignar nombre automático (por defecto, "pc").
901         NAME="$(ogGetHostname)"
902         NAME=${NAME:-"pc"} ;;
903    3)   # Asignar nombre del 3er parámetro.
904         NAME="$3" ;;
905    *)   # Formato de ejecución incorrecto.
906         ogRaiseError $OG_ERR_FORMAT
907         return $?
908esac
909
910# Montar el sistema de archivos.
911MNTDIR=$(ogMount $1 $2) 2>/dev/null
912[ -n "$MNTDIR" ] || ogRaiseError OG_ERR_PARTITION "$1, $2" || return $?
913
914ETC=$(ogGetPath $1 $2 /etc)
915
916if [ -d "$ETC" ]; then
917        #cambio de nombre en hostname
918        echo "$NAME" > $ETC/hostname
919        #Opcion A para cambio de nombre en hosts
920        #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts
921        #Opcion B componer fichero de hosts
922        cat > $ETC/hosts <<EOF
923127.0.0.1       localhost
924127.0.1.1       $NAME
925
926# The following lines are desirable for IPv6 capable hosts
927::1     ip6-localhost ip6-loopback
928fe00::0 ip6-localnet
929ff00::0 ip6-mcastprefix
930ff02::1 ip6-allnodes
931ff02::2 ip6-allrouters
932EOF
933fi
934}
935
936
937###
938#En pruebas
939##
940#/**
941#         ogCleanLinuxDevices int_ndisk int_nfilesys
942#@brief   Limpia los dispositivos del equipo de referencia. Interfaz de red ...
943#@param   int_ndisk      nº de orden del disco
944#@param   int_nfilesys   nº de orden del sistema de archivos
945#@return  (nada)
946#@exception OG_ERR_FORMAT    Formato incorrecto.
947#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
948#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
949#@version 1.0.5 - Primera versión para OpenGnSys.
950#@author  Antonio J. Doblas Viso.   Universidad de Malaga.
951#@date    2013-03-21
952#*/ ##
953function ogCleanLinuxDevices ()
954{
955# Variables locales.
956local MNTDIR
957
958# Si se solicita, mostrar ayuda.
959if [ "$*" == "help" ]; then
960    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
961           "$FUNCNAME 1 1"
962    return
963fi
964# Error si no se reciben 2 parámetros.
965[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
966
967# Montar el sistema de archivos.
968MNTDIR=$(ogMount $1 $2) 2>/dev/null
969[ -n "$MNTDIR" ] || ogRaiseError OG_ERR_PARTITION "$1, $2" || return $?
970
971# Eliminar fichero de configuración de udev para dispositivos fijos de red.
972rm -f ${MNTDIR}/etc/udev/rules.d/70-persistent-net.rules
973}
974
Note: See TracBrowser for help on using the repository browser.