summaryrefslogtreecommitdiffstats
path: root/vmware/runvmware
blob: 073015399929297766d4a057a20e213d112c09ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
#!/bin/sh
#
# Description:  Script for preparing VMware environment Diskless
#               X Stations and interactive session chooser (v4)
#
# Author(s):    Dirk von Suchodoletz <dirk@goe.net>, 18-03-2006
#               Michael Janczyk <mj0@uni-freiburg.de>, 27-03-2007
# Copyright:    (c) 2003, 2006 - RZ Universitaet Freiburg
#
# Version:      0.17.831
#
################################################################################


### VERBOSE?/PATH ##############################################################
# set verbose mode (set -x(v))
#set -xv
export PATH="${PATH}:/var/X11R6/bin:/usr/X11R6/bin"


### HEADER SECTION #############################################################
# write runvmware.conf
runvmwareconfheader ()
{
  echo "
  ##############################################################################
  ###### This configuration file was generated by 'runvmware',            ######
  ###### dont use it for your own configurations - it will be overwritten ######
  ######                                                                  ######

  ###### identity ##############################################################
  displayName = \"${displayname}\"
  guestOS = \"${vmostype}\"
  config.version = \"${confver}\"
  virtualHW.version = \"${hver}\"

  memsize = \"${mem}\"
  numvcpus = \"1\"

  ###### ide-disks #############################################################
  ide0:0.mode = \"${np}\"
  ide0:0.present = \"${ide}\"
  ide0:0.fileName = \"${diskfile}\" 

  ide1:0.present = \"${cdr_1}\"
  ide1:0.autodetect = \"TRUE\"
  ide1:0.fileName = \"auto detect\"
  ide1:0.deviceType = \"cdrom-raw\"

  ide1:1.present = \"${cdr_2}\"
  ide1:1.autodetect = \"TRUE\"
  ide1:1.fileName = \"auto detect\"
  ide1:1.deviceType = \"cdrom-raw\"

  ###### scsi-disks ############################################################
  scsi0.present = \"${scsi}\"
  scsi0.virtualDev = \"${hddrv}\"
  scsi0:0.mode = \"${np}\"
  scsi0:0.present = \"${scsi}\"
  scsi0:0.fileName = \"${diskfile}\"

  ###### nics ##################################################################
  ethernet0.present = \"TRUE\"
  ethernet0.addressType = \"static\"
  ethernet0.connectionType = \"bridged\"
  ethernet0.address = \"00:50:56:0D:${mac}\"

  ###### sound #################################################################
  sound.present = \"TRUE\"
  sound.virtualDev = \"es1371\"

  ###### usb ###################################################################
  usb.present = \"TRUE\"
  usb.generic.autoconnect = \"TRUE\"

  ###### floppies ##############################################################
  floppy0.present = \"${floppya}\"
  floppy0.fileName = \"auto detect\"

  floppy1.present = \"${floppyb}\"
  floppy1.fileType = \"file\"
  floppy1.fileName = \"${floppybname}\"
  floppy1.startConnected = \"TRUE\"

  ###### ports #################################################################
  parallel0.present = \"FALSE\"

  serial0.present = \"FALSE\"

  ###### shared folders ########################################################
  sharedFolder0.present = \"TRUE\"
  sharedFolder0.enabled = \"TRUE\"
  sharedFolder0.expiration = \"never\"
  sharedFolder0.guestName = \"Home\"
  sharedFolder0.hostPath = \"${HOME}\"
  sharedFolder0.readAccess = \"TRUE\"
  sharedFolder0.writeAccess = \"TRUE\"
  sharedFolder.maxNum = \"1\"

  ###### misc ##################################################################
  tmpDirectory = \"${tmpdir}\"
  mainMem.useNamedFile = \"FALSE\"
  snapshot.disabled = \"TRUE\"
  tools.syncTime = \"TRUE\"
  redoLogDir = \"${tmpdir}\"
  hints.hideAll = \"TRUE\"
  logging = \"FALSE\"
  isolation.tools.hgfs.disable = \"FALSE\"
  isolation.tools.dnd.disable = \"TRUE\"
  isolation.tools.copy.enable = \"TRUE\"
  isolation.tools.paste.enabled = \"TRUE\"
  gui.restricted = \"TRUE\"
  pref.hotkey.shift = \"TRUE\"
  pref.hotkey.control = \"TRUE\"
  pref.hotkey.alt = \"TRUE\"
  svga.maxWidth = \"${xres}\"
  svga.maxHeight = \"${yres}\"
  " \
  >${confile}

  # set the appropriate permissions for the vmware config file
  chmod u+rwx ${confile} >/dev/null 2>&1
}


preferencesheader ()
{
  echo "
  ##############################################################################
  ###### This configuration file was generated by 'runvmware',            ######
  ###### dont use it for your own configurations - it will be overwritten ######
  ######                                                                  ######
  ################################## Wichtig! ##################################
  ###### *.vmem wird immer angelegt und frisst soviel Speicher, wie fuer  ######
  ###### den Gast vorgesehen. Sollte nicht im tempfs liegen. NFS OK, da   ######
  ###### IO nur einmal beim Start erheblich. Wird gesteuert ueber         ######
  ###### tmpDirectory = /nfs-viel-platz und darin wird dann vmware-\$user ######
  ###### angelegt.                                                        ######

  hints.hideAll = \"TRUE\"
  pref.exchangeSelections = \"TRUE\"
  pref.hotkey.shift = \"TRUE\"
  pref.tip.startup = \"FALSE\"
  pref.vmplayer.exit.vmAction = \"poweroff\"
  pref.vmplayer.fullscreen.autohide = \"TRUE\"
  pref.vmplayer.webUpdateOnStartup = \"FALSE\"
  prefvmx.defaultVMPath = \"${vmhome}\"
  prefvmx.mru.config = \"${confile}:\"
  tmpDirectory = \"${tmpdir}\"
  webUpdate.checkPeriod = \"manual\"
  pref.eula.size = \"2\"
  pref.eula.0.appName = \"VMware Player\"
  pref.eula.0.buildNumber = \"${vmbuild}\"
  pref.eula.1.appName = \"VMware Workstation\"
  pref.eula.1.buildNumber = \"${vmbuild}\"
  " \
  >${vmhome}/preferences
}


### VARIABLES SECTION ##########################################################
# declaration of default variables
# script variables
last_changes=$(head -n 15 $0 | grep "@" | awk -F ", " '{print $2}' \
  | awk -F "-" '{print $3" "$2" "$1}' | sort -bfnr \
  | awk '{print $3"-"$2"-"$1}' | grep -m 1 [0-9])
version=$(head -n 15 $0 | grep "# Version: " | awk '{print $3}')

# hardware variables
# temporary disk space for logs, etc...
preftmpdir=/tmp/${USER}
# there are two different kinds of tmp needed:
# user config -> preferences for all *.vmx (especially that hidden ram image)
# and per vmx config (written to runvmware.conf)
if cat /proc/mounts|grep -e " /tmp" 2>/dev/null| grep -e "nfs" &>/dev/null
  then export tmpdir=/dev/shm/vmware
else
  export tmpdir=$preftmpdir
fi

mac=
declare -i mem=0
declare -i memtest=0
memopt=
memhost=
memmeg=
memgig=
permem=66
# virtual devices
ide="TRUE"
scsi="FALSE"
hddrv="lsilogic"
cdr_1="FALSE"
cdr_2="FALSE"
floppya="FALSE"
floppyb="FALSE"
# place for the virtual floppy "B:"
floppybname="/etc/vmware/loopimg/fd.img"
# resolution
hostres=$(xvidtune -show 2>/dev/null| grep -ve "^$")
xres=$(echo "${hostres}" | awk '{print $3}')
yres=$(echo "${hostres}" | awk '{print $7}')
guestres=
g_xres=
g_yres=

# VMware variables
# VMware start options
vmopt="-X -q"
# configfile
confile="${tmpdir}/runvmware.conf"
vmhome="${HOME}/.vmware"
vmdir="/var/lib/vmware"
# templates dir
vmtempl="${vmdir}/templ"
# .desktop files directory
xsessions="/usr/share/xsessions"
vmsessions="/etc/X11/sessions/runvmware"
themesdir="/var/lib/openslx/themes"
desktops=( `ls ${vmsessions}/*.desktop 2>/dev/null` )
desktopsnr=$(echo "${#desktops[*]}")
dialogtitle='--title "VMware Image Menu"'
execute=()
menu=
# special Variables
confver=8
hver=4
np="independent-nonpersistent"
# set hostname: using original hostname and adding string "-vm"
hostname="VM-${HOST}"
# set samba workgroup
workgroup="VMware-Workgroup"
comment="Diskless X Station VMware Image"
# image variables
alias=
diskfile=
rightsfile=
noimage=0
ostype=
vmostype=
displayname="Diskless X Station VMware Image"
# image checking variable
filecheck=

# command line variables
# start with this this default commmand line options + extra
defaults=$(grep -v "#.*" ${vmtempl}/defaults)
# add command line opts to defaults
# defaults will be overwritten by command line options
lineopts=( `echo ${defaults} $@` )
nofclopt=$(expr $# + $(echo ${defaults} | wc -w))
silent=
include=
debug=0
istart=
xdm=
comdef=


### FUNCTIONS SECTION ##########################################################
# function to write to stdout/logfile
# logs labeled with $2=0 write to stdout, if debug set, write to logfile
writelog ()
{
  # write to stdout
  [ -z ${silent} ] && [ "$2" = "0" ] && echo -e "$1"
  
  # check if range given e.g. 0 0
  if [ -z "$2" ] || [ -z "$3" ];then
    echo -e "\n\nNO RANGE IN WRITELOG STATEMENT:\n$1\n\tPlease correct!\n"
    exit 1
  fi

  # log if level greater than 1 and log only from level $2 to level $3
  [ "${debug}" -ge "1" ] && [ "${debug}" -ge "$2" ] && [ "${debug}" -le "$3" ] \
    && echo -e "$1" >>${tmpdir}/runvmware.${debug}.log
}


help ()
{
 cat <<EOH

USAGE: $0 [--options]

Image options:
	-i|--interactive        interactive mode with image selection
        --xdm <all|vm>          all lists xdm sessions and VMware images,
                                vm lists only VMware images, use only w/ xdm
        -s|--start <image-name>	start image /\${vmdir}/<image-name>.vmdk
	-a|--alias		use aliases
	--silent		no stdout from runvmware
        --mem <n(M(h))|n(G(h))>	override autoallocation of memory, in percent
                                m,M megabyte, g,G gigabyte, h,H reserve f. host
        --res <X_intxY_int>     Maximum resolution of the guest os, e.g. 800x600
	--delay <n seconds>	delay the start of the script n seconds
	--image <directory>	specify image directory
	--persistent		use persistent mode
	--vmostype <vmwareos>   define VMware ostype
        --include <includefile> include code right before program start
	--displayaliases	aliases you can use with option -a
        --floppya               enable floppy disk
        --floppyb               use /etc/vmware/fd-loop as floppy B,
                                needed for exchanging files w/ VMware
VMware options:
        --run <program>         specify programm, e.g. vmware, vmplayer, ...
	--windowed		start in windowed mode
	--edit			only open config file in vmware (only VMware)
	--donotquit		do not quit after image stopped (only VMware)
runvmware options:
	-h|--help		this help
	--version
	--debug <level>		level 1 -> print stdout to file

		Dirk von Suchodoletz,     Michael Janczyk
		  <dirk@goe.net>,      <mj0@uni-freiburg.de>

EOH

  # print version , remove path
  echo -e "$0: LAST CHANGES $last_changes | VERSION $version\n" \
    | awk -F "/" '{print "\t\t"$NF}'

  exit 0
}


checkalias ()
{
  if [ -r "${vmtempl}/alias" ]; then

    writelog "Checking alias for ${startvm}...\c" 0 1

    vmalias=$(grep -v "#.*" ${vmtempl}/alias | grep -w "${startvm}" \
      | awk '{print $1}')
    [ -n "${vmalias}" ] && startvm=${vmalias}

    writelog "finished\nResult:\n\tVMimage name:\t${startvm}\n" 0 1

  else
    writelog "NO alias file found: ${vmtempl}/alias" 0 1
    writelog "Try without option \"-a\"" 0 1
    exit 1

  fi
}


xdm_mode ()
{
  # Xdailog test
  xdialog=$(which Xdialog)
  [ -z "${xdialog}" ] && \
    xterm -e 'echo -e "\n\n\n\n\n\n\t\t\tNo Xdialog installed!!!\  
    \n\n\t\t\tClosing in 3 seconds."; sleep 3' && exit 1

  # set X background
  res=$(xvidtune -show | grep -wo "\".*\"" | sed "s/\"//g") 
  if ! [ -f ${themesdir}/bootsplash/images/silent-${res}.jpg ]; then     
    img=$(ls ${themesdir}/bootsplash/images/ | grep -m 1 "silent")
    display -window root ${themesdir}/bootsplash/images/${img}
  else
    display -window root ${themesdir}/bootsplash/images/silent-${res}.jpg
  fi
  
  dialogtitle='--rc-file ${themesdir}/Xdialog/gtkrc \
    --title "VMware Image Menu"'
    
  if [ "${xdm}" = "all" ]; then
    desktops=( `ls ${xsessions}/*.desktop 2>/dev/null \
      | grep -v "default.*" | sort -bf; \
      ls ${vmsessions}/*.desktop 2>/dev/null | sort -bf` )
    desktopsnr=$(echo "${#desktops[*]}")
    dialogtitle='--rc-file ${themesdir}/Xdialog/gtkrc \
      --title "Desktop / VMware-Image Menu"'        
  fi
}


x_dialog ()
{
  (( args=0 ))
  declare -i i=0

  while [ "${desktopsnr}" -gt "${args}" ]; do

    # exec in .desktop
    execute[${i}]=$(grep -m 1 -i "exec" ${desktops[${args}]} \
      | awk -F "=" '{print $2}')
    menu="$menu \"\${execute[${i}]}\""
    i=${i}+1

    # name in .desktop
    execute[${i}]=$(grep -m 1 -i "name" ${desktops[${args}]} \
      | awk -F "=" '{print $2}')
    execute[${i}]=${execute[${i}]:-`echo ${execute[${i}-1]} | sed -e "s,-, ,g"`}
    menu="$menu \"\${execute[${i}]}\""
    i=${i}+1

    # comment in .desktop
    execute[${i}]=$(grep -m 1 -i "comment" ${desktops[${args}]} \
      | awk -F "=" '{print $2}')
    execute[${i}]=${execute[${i}]:-"No comment"}
    menu="$menu \"\${execute[${i}]}\""
    i=${i}+1

    (( args=${args}+1 ))
  done
 
  # test if menu not empty?
  if [ -z "${menu}" ]; then
    Xdialog --infobox "No items found to display!!!
    For Vmware images add .desktop files to
    ${vmsessions}" 10 50 6000
    exit 1
  fi

  # echoing to file because Xdialog sux when used w/ quotes
  echo -e "Xdialog ${dialogtitle} \
          --screen-center \
          --fill \
          --no-wrap \
          --stdout \
          --no-tags \
          --ok-label \"START\" \
          --item-help \
          --menubox \"Please choose the image you would like to run:\" 35 80 0 \
          $menu 2>/dev/null" \
  > ${tmpdir}/Xdialog
  
. ${tmpdir}/Xdialog
rm -f ${tmpdir}/Xdialog
}

x_dialog_check ()
{
  if ! [ `which Xdialog 2>/dev/null` ]; then
    writelog "\rXdialog not found!      " 0 99
    writelog "Please install Xdialog for interactive mode, \c" 0 0
    writelog "or use option -s.\n" 0 0
    # for non-console starts
    xterm -e 'echo -e "\n\n\n\n\n\n\t\t\tNo Xdialog installed!!!\
      \n\n\t\t\tClosing in 3 seconds."; sleep 3'
    exit 1
  fi
}


filecheck ()
{
  filecheck=$(LANG=us ls -lh ${diskfile} 2>&1)
  writelog "Filecheck:\n${filecheck}\n" 0 1
  noimage=$(echo ${filecheck} | grep -i "no such file or directory" | wc -l)
  rightsfile=${diskfile}

  # check if link
  if [ -L "${diskfile}" ]; then
    # take link target
    rightsfile=$(ls -lh ${diskfile} 2>&1 | awk -F "-> *" '{print $2}')
    rightsfile=${vmdir}/${rightsfile}
    filecheck=$(LANG=us ls -lh ${rightsfile} 2>&1)
  fi

  # does file exist
  if [ "${noimage}" -ge "1" ]; then
    writelog "Vmware Image Problem:\c" 0 0
    writelog "\tThe image you've specified doesn't exist." 0 0
    writelog "Filecheck says:\c" 0 1
    writelog "\t\t${diskfile}:\n\t\t\tNo such file or directory" 0 1
    writelog "Hint:\c" 0 0
    writelog "\t\t\tCompare spelling of the image with your options.\n" 0 0
    exit 1
  fi

  # readable?
  if ! [ -r "${diskfile}" >/dev/null 2>&1 \
    -o -r "${diskfile}" >/dev/null 2>&1 ]; then
    writelog "Vmware Image Problem:\c" 0 1
    writelog "\tThe image you've specified has wrong rights." 0 1
    writelog "Filecheck says:\t\t`echo ${filecheck} \
      | awk '{print $1" "$3" "$4}'` ${rightsfile}" 0 1
    writelog "Hint:\t\t\tChange rights with: chmod a+r ${rightsfile}\n" 0 0
    exit 1
  fi

  # writable (for persistent-mode)?
  if ! [ -w "${diskfile}" >/dev/null 2>&1 \
    -o -w "${diskfile}" >/dev/null 2>&1 ] \
    && [ "${np}" = "independent-persistent" ]; then
    writelog "Vmware Image Problem:\c" 0 1
    writelog "\tThe image you've specified has wrong rights." 0 1
    writelog "Filecheck says:\t\t`echo ${filecheck} \
      | awk '{print $1" "$3" "$4}'` ${rightsfile}" 0 1
    writelog "Hint:\t\t\tUse nonpersistent-mode or change rights to rw\n" 0 0
    exit 1
  fi
}


#### INTERPRET COMMAND LINE OPTIONS ############################################
# print help if no clo
if [ ${nofclopt} = "0" ]; then
  help
  exit 0
fi

# interpretation of command line arguments
(( args=0 ))
while [ ${nofclopt} -gt "${args}" ]; do
  case "${lineopts[${args}]}" in
    -h|--help)
      help
    ;;
    --version)
      echo -e "\n$0: LAST CHANGES ${last_changes} | VERSION ${version}\n" \
        | awk -F "/" '{print "\t"$NF}'
      exit 0
    ;;
    -i|--interactive)
      istart="TRUE"
    ;;
    --xdm)
      (( args=${args}+1 ))
      xdm=${lineopts[${args}]}
      xdmstart="TRUE"
    ;;
    -s|--start)
      (( args=${args}+1 ))
      startvm=${lineopts[${args}]}
      sstart="TRUE"
    ;;
    -a|--alias)
      alias="TRUE"
    ;;
    --silent)
      silent="TRUE"
    ;;
    --displayaliases)
      cat ${vmtempl}/alias; exit 0
    ;;
    --delay)
      (( args=${args}+1 ))
      sleep ${lineopts[${args}]}
    ;;
    --image)
      (( args=${args}+1 ))
      vmdir=${lineopts[${args}]}
    ;;
    --persistent)
      np="independent-persistent"
    ;;
    --include)
      (( args=${args}+1 ))
      include=${lineopts[${args}]}
    ;;
    --vmostype)
      (( args=${args}+1 ))
      vmostype=${lineopts[${args}]}
      comdef="TRUE"
    ;;
    --mem)
      (( args=${args}+1 ))
      memopt=${lineopts[${args}]}
    ;;
    --res)
      (( args=${args}+1 ))
      guestres=${lineopts[${args}]}
    ;;
    --run)
      (( args=${args}+1 ))
      vmrun=${lineopts[${args}]}
    ;;
    --debug)
      (( args=${args}+1 ))
      debug=${lineopts[${args}]}
    ;;
    --windowed)
      vmopt=$(echo ${vmopt} | sed -e "s,-X,-x,")
    ;;

    --floppya)
      floppya="TRUE"
    ;;
    --floppyb)
      floppyb="TRUE"
    ;;
    --edit)
      vmopt=""
    ;;
    --donotquit)
      vmopt=$(echo ${vmopt} | sed -e "s,-q,,")
    ;;
    *)
    echo -e "\n\tOption\"${lineopts[${args}]}\" not found, please correct.\n"
    sleep 1
    help
  ;;
  esac
  (( args=${args}+1 ))
done


### STARTING ###################################################################
# create environment
# remove leftover locks from former runs,
# problems may occure if you run more then one vmware with this script
rm -f ${tmpdir}/*LOCK >/dev/null 2>&1
rm -f ${tmpdir}/*.${debug}.log >/dev/null 2>&1

# create vmware directories
mkdir -p ${tmpdir} >/dev/null 2>&1
mkdir -p ${vmhome} >/dev/null 2>&1

# NO X-server no runvmware ;)
[ -z "$DISPLAY" ] && echo -e "\n\tStart only within a desktop!\n" && exit 1

# if --xdm set don't go further, only used for xdm starts
if [ "${xdm}" = "all" -o "${xdm}" = "vm" ]; then
  x_dialog_check
  xdm_mode
  args_dial=$(x_dialog)
  exec ${args_dial}
  exit 0
elif [ -n "${xdmstart}" -a -z "${xdm}" ]; then
  xterm -e 'echo -e "\n\n\n\n\n\n\t\t\tWrong --xdm option! \
    \n\t\t\tOnly all or vm possible.\
    \n\n\t\t\tClosing in 3 seconds."; sleep 3' && exit 1
fi

# if not interactive mode or image spezified via command line stop
if [ -z "${istart}" -a -z "${sstart}" ]; then
  writelog "\n\tSpecify image to start /w -s or run interactive mode -i!\n" 0 0
  exit 1
fi

# logo for console
if [ -z ${silent} ]; then
cat <<EOL

           .----.--.--.-----.--.--.--------.--.--.--.---.-.----.-----.
           |   _|  |  |     |  |  |        |  |  |  |  _  |   _|  -__|
           |__| |_____|__|__|\___/|__|__|__|________|___._|__| |_____|
                Script for preparing VMware environment...(v${version})


EOL
writelog "Starting...`echo ${np} | sed -e \"s,i.*-,,g\" \
  | tr [a-z] [A-Z]`-mode\n" 0 0

fi


### CHECK MACHINE SETUP ########################################################
# start logging, because now we have the directories created ;)
writelog "##################################################" 1 99
writelog "#\n# File created by $0 (v.${version})\n# on `date`"  1 99
writelog "# LOGLEVEL=${debug}\n#" 1 99
writelog "##################################################\n" 1 99
# repeat only for logfile ;)
writelog "Starting...`echo ${np} | sed -e \"s,i.*-,,g\" \
  | tr [a-z] [A-Z]`-mode\n" 1 1

# log disksetup
writelog "Directories:
  \tTmpdir:\t\t${tmpdir}\n\tVMhome:\t\t${vmhome}\n\tTmpdir info:\
  \t`mount | grep -i "/tmp "`\n" 0 1

# configuring MAC address: first four bytes are fixed (00:50:56:0D) the
# last two bytes are taken from the local network adaptor
writelog "Starting hardware / device detection...\c" 0 1

mac=$(/sbin/ifconfig eth0 | grep eth0 | sed -e "s, ,,g" \
  | awk -F ":" '{print $(NF-1)":"$NF}')

# get memory in MB
memtest=$(expr $(grep -i "memtotal" /proc/meminfo | awk '{print $2}') / 1024)

# check if command line option given and calculate memory for vmware
if [ -n "${memopt}" ]; then
  # memory allocation for host or guest?
  memhost=`echo ${memopt} | grep -i "h"`\
    && memopt=`echo ${memopt} | sed -e "s,[h,H],,"`
  # memory given in megabyte
  memmeg=`echo ${memopt} | grep -i "m"`
  # memory given in gigabyte
  memgig=`echo ${memopt} | grep -i "g"`
  # remove m or M
  [ -n "${memmeg}" ] && mem=$(echo ${memopt} | sed -e "s,[m,M],,")
  # remove g or G and convert to megabyte
  [ -n "${memgig}" ] && mem=$(echo ${memopt} | sed -e "s,[g,G],,") \
     && mem=${mem}*1024
  # if no m or g, then it is percent
  [ -z "${memmeg}" ] && [ -z "${memgig}" ] && mem=${memtest}/100*${memopt}/4*4
  # memory allocation for host or guest? If host calculate for guest.
  [ -n "${memhost}" ] && mem=${memtest}-${mem}
  # else use ${permem} variable to calculate memory percentage for vmware
else mem=${memtest}/100*${permem}/4*4
fi

# check memory range
memtest=${memtest}-128
if [ "${mem}" -lt "128" ] || [ "${mem}" -gt "${memtest}" ]; then
  writelog "\n\n\tYour memory is out of range: ${mem} MB.
    \tMin. 128 MB for host and guest!\n\tTry --mem option.\n" 0 1
  exit 1
fi

# look for cdrom,dvd and floppy and add them to the vm config file
if [ -L /dev/cdrom ] ; then
  cdr_1="TRUE"
fi

if [ -L /dev/cdrom1 ] ; then
  cdr_2="TRUE"
fi

# check for floppy controller
test ! -d /sys/block/fd0 && floppya="FALSE"

# guest resolution
if [ -n "${guestres}" ]; then
  g_xres=$(echo "${guestres}" | awk -F "x" '{print $1}')
  g_yres=$(echo "${guestres}" | awk -F "x" '{print $2}')
  if [ "${g_xres}" -ge "640" -a "${g_xres}" -le "${xres}" \
    -a "${g_yres}" -ge "480" -a "${g_yres}" -le "${yres}" ]; then
    xres=${g_xres}
    yres=${g_yres}
  else
    writelog "\n\n\tSpecified resolution is not in range!
      \tRange: 640x480 - ${xres}x${yres}
      \tJumping back to resolution of Host.\n"
  fi
fi        

writelog "finished\nResults:\n\tMAC:\t\t00:50:56:0D:${mac}\n\tMem:\t\t${mem} MB
  \tMax. res.:\t${xres}x${yres}\n\tFloppy_A:\t${floppya}\n\tFloppy_B:\
  \t${floppyb}\n\tCD-ROM_1:\t${cdr_1}\n\tCD-ROM_2:\t${cdr_2}\n" 0 1


### SELECT VIRTUAL IMAGE #######################################################
# interactive mode
if [ -n "${istart}" ]; then
  writelog "Starting interactive mode...\c" 0 0

  # check for session files
  if [ -z "${desktops}" ]; then
    writelog "\rNo .desktop files found in ${vmsessions} for option -i" 0 99
    writelog "Please use option -s and check your configuration \n" 0 0 
    exit 1
  fi

  # check for Xdialog
  x_dialog_check

  # create menu, etc...
  startvm=$(x_dialog)

  if [ -z "${startvm}" ]; then
    writelog "\rNo image selected, please retry or use option -s\n" 0 0
    writelog "No image was selected (option -i); \c" 2 2
    writelog "return value is: ${startvm}\n" 2 2
    exit 1
  fi

  writelog "finished.\nResult:\n\tVMimage:\t${startvm}\n" 0 1
fi

# aliases
[ -n "${alias}" ] && checkalias

# image allocation
writelog "Starting image detection...\c" 0 1

diskfile="${vmdir}/${startvm}.vmdk"

# check if IDE or SCSI
hddrv=$(grep -m 1 -ia "ddb.adapterType" ${diskfile} | awk -F "\"" '{print $2}')
if [ "${hddrv}" = "ide" ]; then
  ide="TRUE"
  scsi="FALSE"
elif [ "${hddrv}" = "lsilogic" ]; then
  ide="FALSE"
  scsi="TRUE"  
elif [ "${hddrv}" = "buslogic" ]; then
  ide="FALSE"
  scsi="TRUE"  
fi

# check if ${vmostype} defined via command line
if [ -z "${comdef}" ]; then
  ostype=$(echo ${startvm} | awk -F "-" '{print $1}')
  vmostype=$(grep -v "#.*" ${vmtempl}/ostype | grep -w "${ostype}" \
    | awk '{print $1}')

  # if ${ostype} not found use else statement
  vmostype=${vmostype:-"other"}
fi

# define name for VMware window
displayname=$(grep -m 1 -i "name" \
  ${vmsessions}/*${startvm}.desktop | awk -F "=" '{print $2}')
# if variable not set
displayname=${displayname:-"VMware Image"}

writelog "finished\nResults:\n\tDiskfile:\t${diskfile}\n\tDisktype:\t${hddrv}
  \tVMostype:\t${vmostype}\n\tDisplayname:\t${displayname}\n" 0 1

# check if image exists, etc...
filecheck


### WRITE CONFIGURATION FILES / RUN VMWARE(-Player) ############################
# ...with the automatically written config file

# include file which is given via command line
[ -n "${include}" ] && . ${include}

# copy VMware (-Player) bios
cp ${vmtempl}/nvram.5.0 ${tmpdir}/nvram 2>&1 >/dev/null

# adjust volume
writelog "Unmuting sound...\c" 0 0
amixer -q sset Master 28 unmute
amixer -q sset PCM 28 unmute
writelog "finished\n" 0 0

if [ `which vmplayer 2>/dev/null` ] && [ -z "${vmrun}" ] \
  || [ "${vmrun}" = "vmplayer" ]; then
  
  # VMware build
  vmbuild=$(vmplayer -v | awk -F "-" '{print $2}')

  # create preferences
  preferencesheader

  # create VMware startup file
  runvmwareconfheader
  
  writelog "\nStarting VMplayer..." 0 0
  vmopt=$(echo ${vmopt} | sed -e "s,-q,," -e "s,-x,,") # remove unsupported opts
  # run VMplayer
  vmplayer ${vmopt} ${confile} 2>&1 >/dev/null

elif [ `which vmware 2>/dev/null` ] && [ -z "${vmrun}" ] \
  || [ "${vmrun}" = "vmware" ]; then

  # VMware build
  vmbuild=$(vmware -v | awk -F "-" '{print $2}')

  # create preferences
  preferencesheader

  # create VMware startup file
  runvmwareconfheader

  # copy licence file to VMware directory
  cp /var/lib/vmware/templ/license.ws.5.0 ${vmhome} 2>&1 >/dev/null
  writelog "\nStarting VMware..." 0 0
  # run VMware
  vmware ${vmopt} ${confile} 2>&1 >/dev/null

else
  writelog "\nNo VMware/VMPlayer found!\n" 0 99
  exit 1
fi

writelog "\nBye. \n" 0 0
exit 0
################################################################################