Updated pnd_run.sh with the version planned for HF6
[pandora-libraries.git] / testdata / scripts / pnd_run.sh
1 #!/bin/bash
2  
3 #/etc/sudoers needs to be adjusted if you touch any of the sudo lines
4  
5 # look at the comments in the CLOSE_X part, adjust 
6 #use "lsof /usr/lib/libX11.so.6 | awk '{print $1}'| sort | uniq > whitelist" with nothing running to generate the whitelist
7  
8 #todo - no proper order
9 #validate params better
10 #make uid/pnd_name mandatory (and rename var, its confusing!)
11 #find a clean way of shutting down x without a fixed dm, mabye avoid nohup usage somehow
12 #add options to just mount iso without union and to mount the union later
13
14 #SCRIPT_DIR=$(echo $(dirname $(which $0))|sed 's#^\.#'"$(pwd)"'#')
15 #. $SCRIPT_DIR/pnd_loging
16 #PND_LogDateFormat=PND_Time
17
18 #PND_MOUNT_DIR="/mnt/pnd"
19 PND_MOUNT_DIR="/mnt/utmp"
20 UNION_MOUNT_DIR="/mnt/utmp"
21 CPUSPEEDSCRIPT=/usr/pandora/scripts/op_cpuspeed.sh
22
23 #=============================================================================
24 # Log functions
25
26 PND_isInteractive=0
27 PND_Start() {
28         if [ $(ps -o tty,pid 2>/dev/null|grep $$|awk 'BEGIN{R=0}/pts/{R=1}END{print R}') -eq 1 ];then
29                 PND_isInteractive=1
30                 exec 3>&1       # duplicate stdout so we can still write to screen after the log redirect
31         fi
32         {
33         echo "======================================================================================="
34         for v in $PND_HEADER;do
35                 printf "%-15s : %s\n" "$v"  "$(eval "echo \${$v:-'<unset>'}")"
36         done
37         echo "======================================================================================="
38         }>$PND_LOG
39 }
40
41 PND_checkLog() {
42 awk 'BEGIN{R=0}END{exit R}
43 /cannot open display/||/unary operator expected/||/No such file or directory/||/command not found/{R=R+1}
44 {IGNORECASE=1}
45 !/gpg-error/&&/ERROR/||/FAILED/{R=R+1}
46 {IGNORECASE=0}' < $PND_LOG
47 }
48
49 PND_Stop() {
50         local RC=$?
51         PND_checkLog
52         RC=$(( $RC + $? ))      # trying to find error in the logs
53         {
54         echo "======================================================================================="
55         echo "Return code is : $RC"
56         }>>$PND_LOG
57         return $RC
58 }
59
60 PND_BeginTask() {
61         export PND_TASK_NAME="$*"
62         echo "[ START ]--- $PND_TASK_NAME ----------"
63         if [ $PND_isInteractive -eq 1 ];then
64                 printf "$PND_TASK_NAME"  >&3
65         fi
66 }
67
68 PND_EndTask() {
69         local RC="$?"
70         local STATUS=""
71         local COLOR=""
72         local X=""
73         if [ $RC -eq 0 ];then 
74                 STATUS=SUCCESS
75                 COLOR="\\033[32m"
76         else
77                 STATUS=FAILED
78                 COLOR="\\033[31m"
79         fi
80         
81         printf "[%7s]--- $PND_TASK_NAME ----------\n" "$STATUS"
82         if [ $PND_isInteractive -eq 1 ];then
83                 printf "\r%s\033[70G[$COLOR%7s\033[m]\n" "$PND_TASK_NAME" "$STATUS" >&3
84         fi
85         unset PND_TASK_NAME
86         return $RC
87 }
88
89 PND_WaitFor() {
90         [ $# -gt 0 ]||return 1
91         local l_test="$1"
92         local l_name=${2:-"Wait succes of $1"}
93         local l_cnt=${3:-12}
94         local l_sleep=${4:-10}
95         local C=0
96         PND_BeginTask $l_name
97         while [ $C -lt $l_cnt ] && ! eval $l_test;do
98                 sleep $l_sleep;C=$(($C + 1));
99         done
100         [ $C -lt $l_cnt ]
101         PND_EndTask
102 }
103
104 PND_Exec() {
105         local CMD="$*"
106         {
107         if [ $PND_ISEXEC -eq 0 ];then
108                 PND_ISEXEC=1
109                 exec 3>&1               # 
110         fi
111         export PND_INTERACTIVE=2
112         $* 2>&1
113         RES=$(( $? + $PND_ERRORS ))
114         echo "<result>$RES</result>"
115         PND_ISEXEC=0
116         exec 3>&-
117         }|{
118         while read line;do
119                 if echo "$line"|grep -q "<result>.*</result>";then
120                         return $(( $(echo $line|sed 's/<[^>]*>//g') + $PND_ERRORS ))
121                 elif ! echo "$line"| $(eval $PND_OUT_CHECK); then
122                         PND_Error "$line";
123                 else
124                         PND_Print "$line";
125                 fi
126         done
127         return $PND_ERRORS
128         }
129 }
130
131
132
133 #=============================================================================
134 # Utility functions
135
136 showHelp() {
137         cat <<endHELP
138 Usage:
139   pnd_run.sh -p file.pnd -e cmd [-a args] [-b pndid] [-s path] [-c speed] [-d [path]] [-x] [-m] [-u]
140     -p file.pnd : Specify the pnd file to execute
141     -e cmd      : Command to run
142     -a args     : Arguments to the command
143     -b pndid    : name of the directory mount-point ($UNION_MOUNT_DIR/pndid) (Default: name of the pnd file)
144     -s path     : Directory in the union to start the command from
145     -o speed    : Set the CPU speed
146     -d [path]   : Use path as source of the overlay. (Default: pandora/appdata/pndid)
147     -x          : Stop X before starting the apps
148     -m          : Only mount the pnd, dont run it (-e become optional)
149     -u          : Only umount the pnd, dont run it (-e become optional)
150 endHELP
151 }
152
153 list_using_fs() {
154         for p in $(fuser -m $1 2>/dev/null);do ps hf $p;done
155 }
156
157
158 #=============================================================================
159 # CPU speed functions
160 PND_getCPUSpeed() {
161         cat /proc/pandora/cpu_mhz_max
162 }
163
164 PND_setCPUSpeed() {
165         unset CURRENTSPEED
166         if ! [ -f "$CPUSPEED_FILE" ] && [ ! -z "$PND_CPUSPEED" ]; then
167                 if [ ${PND_CPUSPEED} -gt $(PND_getCPUSpeed) ]; then 
168                    CURRENTSPEED=$(PND_getCPUSpeed)
169                    case "$(zenity --title="set cpu speed" --height=350 --list --column "id" --column "Please select" --hide-column=1 \
170                                   --text="$PND_NAME suggests to set the cpu speed to $PND_CPUSPEED MHz to make it run properly.\n\n Do you want to change the cpu speed? (current speed: $(PND_getCPUSpeed) MHz)\n\nWarning: Setting the clock speed above 600MHz can be unstable and it NOT recommended!" \
171                                   "yes" "Yes, set it to $PND_CPUSPEED MHz" \
172                                   "custom" "Yes, select custom value" \
173                                   "yessave" "Yes, set it to $PND_CPUSPEED MHz and don't ask again" \
174                                   "customsave" "Yes, set it to custom speed and don't ask again" \
175                                   "no" "No, don't change the speed" \
176                                   "nosave" "No, don't chage the speed and don't ask again")" in
177                         "yes")
178                                 sudo $CPUSPEEDSCRIPT $PND_CPUSPEED
179                                 ;;
180                         "custom")
181                                 sudo $CPUSPEEDSCRIPT
182                                 ;;
183                         "customsave")
184                                 sudo $CPUSPEEDSCRIPT
185                                 zenity --info --title="Note" --text="Speed saved.\n\nTo re-enable this dialogue, please delete the file\n$CPUSPEED_FILE"
186                                 PND_getCPUSpeed > $CPUSPEED_FILE
187                                 ;;
188                         "yessave")
189                                 zenity --info --title="Note" --text="Speed saved.\n\nTo re-enable this dialogue, please delete the file\n$CPUSPEED_FILE"
190                                 sudo $CPUSPEEDSCRIPT $PND_CPUSPEED
191                                 PND_getCPUSpeed > $CPUSPEED_FILE
192                                 ;;
193                         "nosave")
194                                 unset CURRENTSPEED
195                                 zenity --info --title="Note" --text="Speed will not be changed.\n\nTo re-enable this dialogue, please delete the file\n$CPUSPEED_FILE"
196                                 echo 9999 > $CPUSPEED_FILE
197                                 ;;
198                         *)      unset CURRENTSPEED;;
199                   esac
200                fi
201         elif [ "$PND_CPUSPEED" -lt "1500" ]; then
202                 CURRENTSPEED=$(PND_getCPUSpeed)
203                 echo Setting to CPU-Speed $PND_CPUSPEED MHz
204                 sudo $CPUSPEEDSCRIPT $PND_CPUSPEED
205         fi
206 }
207
208 PND_resetCPUSpeed() {
209         if [ ! -z "$CURRENTSPEED" ]; then
210                 sudo $CPUSPEEDSCRIPT $CURRENTSPEED
211         fi
212 }
213
214 #=============================================================================
215 # X management functions
216
217 PND_CloseX(){
218         if [ $CLOSE_X ]; then #the app doesnt want x to run, so we kill it and restart it once the app quits
219                 if [ ! $(pidof X) ]; then 
220                         unset $CLOSE_X
221                 else
222                         applist=$(lsof /usr/lib/libX11.so.6 | awk '{print $1}'| sort | uniq)
223                         whitelist=$(cat ~/pndtest/whitelist) #adjust this to a fixed whitelist, maybe in the config dir
224                         filteredlist=$(echo -e "$applist\n\n$whitelist\n\n$whitelist" | sort | uniq -u) #whitelist appended two times so those items are always removed
225                         if [ ${#filteredlist} -ge 1 ]; then
226                                 message=$(echo -e "The following applications are still running, are you sure you want to close x? \n$filteredlist")
227                                 echo -e "?ae[34me[30m?"
228                                 xmessage -center "$message", -buttons yes,no
229                                 if [ $? = 102 ]; then
230                                         exit 1
231                                 fi
232                                 sudo /etc/init.d/slim-init stop
233                                 sleep 5s
234                         else
235                                 echo -e "?ae[34me[30m?"
236                                 xmessage -center "killing x, nothing of value will be lost", -buttons ok,cancel
237                                 if [ $? = 102 ]; then
238                                         exit 1
239                                 fi
240                                 # close x now, do we want to use slim stop or just kill x?
241                                 sudo /etc/init.d/slim-init stop
242                                 sleep 5s
243                         fi
244                 fi
245         fi
246 }
247
248 PND_RestartX(){
249         if [ $CLOSE_X ]; then #restart x if it was killed
250                 # We need to wait a bit, doing it nicely ;)
251                 sleep 5
252                 sudo /etc/init.d/slim-init start
253         fi
254 }
255
256
257 #=============================================================================
258 # (u)Mounting functions
259
260 show_mounted_info(){
261         echo "+++++++"
262         echo "Loopback devices :"
263         sudo losetup -a
264         echo "Are mounted on :"
265         mount|grep loop
266         echo "For these Union :"
267         mount|grep aufs
268 }
269
270 is_union_mounted() {
271         mount | grep -q "on $UNION_MOUNT_DIR/${PND_NAME} type aufs"
272 }
273
274 is_pnd_mounted() {
275         mount |grep -v aufs | grep -q "on $PND_MOUNT_DIR/${PND_NAME} type"
276 }
277
278 noMoreProcessPnd() {
279         [ -z "$(list_using_fs "$PND_MOUNT_DIR/$PND_NAME")" ]
280 }
281
282 noMoreProcessUnion() {
283         [ -z "$(list_using_fs "$UNION_MOUNT_DIR/$PND_NAME")" ]
284 }
285
286 mountPnd() {
287         if ! is_pnd_mounted;then
288                 #check if pnd is already attached to loop 
289                 LOOP=$(losetup -a | grep "$PND" | tail -n1 | awk -F: '{print $1}')
290                 #check if the loop device is already mounted
291                 if ! [ -z "$LOOP" ];then
292                         echo "Found a loop ($LOOP), using it"
293                         loopmountedon=$( mount | grep "$(mount | grep "$LOOP" | awk '{print $3}')" | grep utmp | awk '{print $3}' )
294                 else
295                         loopmountedon=""
296                 fi
297                 if [ ! "$loopmountedon" ]; then #check if the pnd is already attached to some loop device but not used
298                         FREELOOP=$LOOP 
299                         #reuse existing loop
300                         if [ ! "$LOOP" ]; then
301                                 FREELOOP=$(/sbin/losetup -f) #get first free loop device
302                                 if [ ! "$FREELOOP" ]; then  # no free loop device, create a new one
303                                         #find a free loop device and use it 
304                                         usedminor=$(/sbin/losetup -a | tail -n1|sed 's/.*loop\(.*\)\: .*/\1/')
305                                         #usedminor=${usedminor:9:1}
306                                         freeminor=$(($usedminor+1))
307                                         echo "Creating a new device : mknod -m777 /dev/loop$freeminor b 7 $freeminor"
308                                         mknod -m777 /dev/loop$freeminor b 7 $freeminor
309                                         FREELOOP=/dev/loop$freeminor
310                                 fi
311                         fi
312
313                         #detect fs
314                         case $PND_FSTYPE in
315                         ISO)
316                                 /sbin/losetup $FREELOOP "$PND" #attach the pnd to the loop device
317                                 mntline="mount" #setup the mountline for later
318                                 mntdev="${FREELOOP}"
319                                 ;;
320                         directory)
321                                 #we bind the folder, now it can be treated in a unified way 
322                                 #ATENTION: -o ro doesnt work for --bind at least on 25, on 26 its possible using remount, may have changed on 27
323                                 mntline="mount --bind -o ro"
324                                 mntdev="${PND}"
325                                 ;;
326                         Squashfs)
327                                 /sbin/losetup $FREELOOP "$PND" #attach the pnd to the loop device
328                                 mntline="mount -t squashfs"
329                                 mntdev="${FREELOOP}"
330                                 ;;
331                         *)
332                                 echo "ERROR Unknown filesystem type : $PND_FSTYPE"
333                                 exit 1;;
334                         esac
335                         echo "Mounting : $mntline \"$mntdev\" \"$PND_MOUNT_DIR/${PND_NAME}\""
336                         $mntline "$mntdev" "$PND_MOUNT_DIR/${PND_NAME}" #mount the pnd/folder
337
338                         if ! is_pnd_mounted ;then
339                                 sleep 1
340                                 echo "WARNING : mount faild, re-tring"
341                                 sleep 1
342                                 $mntline "$mntdev" "$PND_MOUNT_DIR/${PND_NAME}" #mount the pnd/folder
343                                 if ! is_pnd_mounted ;then
344                                         echo "ERROR The PND File-system is not mounted !"
345                                         show_mounted_info
346                                         return 2
347                                 fi
348                         fi
349                 else #the pnd is already mounted but a mount was requested with a different basename/uid, just link it there
350                       echo WARNING $LOOP already mounted on $loopmountedon skipping losetup - putting link to old mount
351                       #this is bullshit
352                       rmdir "$UNION_MOUNT_DIR/$PND_NAME"
353                       ln -s $loopmountedon "$UNION_MOUNT_DIR/$PND_NAME" 
354                 fi
355         fi
356 }
357
358 mountUnion() {
359         if [ $(id -u) -ne 0 ];then
360                 sudo /usr/pandora/scripts/pnd_run.sh -m -p "$PND" -b "$PND_NAME"
361                 if ! is_union_mounted;then
362                         echo "ERROR: The Union File-system is not mounted !"
363                         show_mounted_info
364                         return 1
365                 fi
366                 return $RC
367         fi
368         #create mountpoints, check if they exist already first to avoid annoying error messages
369         if ! [ -d "$PND_MOUNT_DIR/${PND_NAME}" ]; then 
370                 mkdir -p "$PND_MOUNT_DIR/${PND_NAME}"           #mountpoint for iso, ro
371         fi 
372         #writeable dir for union
373         if ! [ -d "${APPDATADIR}" ]; then 
374                 mkdir -p "${APPDATADIR}"
375                 chmod -R a+xrw "${APPDATADIR}" 2>/dev/null
376         fi
377         # create the union mountpoint
378         if ! [ -d "$UNION_MOUNT_DIR/${PND_NAME}" ]; then
379                 mkdir -p "$UNION_MOUNT_DIR/${PND_NAME}"         # union over the two
380         fi
381         #is the union already mounted? if not mount evrything, else launch the stuff
382         if ! is_union_mounted;then
383                 if ! is_pnd_mounted;then
384                         mountPnd || return 2; # quit mounting the union if the PND first didnt mount
385                 else
386                         echo "WARNING The PND is already mounted, using it"
387                         show_mounted_info
388                 fi
389                 RO=0;for o in $(mount|awk '$3=="'$MOUNTPOINT'"{print $6}'|sed 's/.*(//;s/)$//;s/,/ /g');do [[ $o = "ro" ]]&& RO=1;done
390                 if [ $RO -eq 1 ];then
391                         echo "WARNING SD-Card is mounted Read-only !! Trying to remount RW"
392                         mount -oremount,rw $MOUNTPOINT
393                 fi
394
395                 if [[ "$APPDD_FSTYPE" = "vfat" ]]; then # use noplink on fat, dont on other fs's 
396                         #append is fucking dirty, need to clean that up
397                         MOUNT_CMD="mount -t aufs -o exec,noplink,dirs=\"${APPDATADIR}=rw+nolwh\":\"$PND_MOUNT_DIR/$PND_NAME=rr$append\" none \"$UNION_MOUNT_DIR/$PND_NAME\""
398                 else
399                         MOUNT_CMD="mount -t aufs -o exec,dirs=\"${APPDATADIR}=rw+nolwh\":\"$PND_MOUNT_DIR/$PND_NAME=rr$append\" none \"$UNION_MOUNT_DIR/$PND_NAME\""
400                 fi
401                 echo "Mounting the Union FS : $MOUNT_CMD"
402                 eval $MOUNT_CMD
403
404                 if ! is_union_mounted;then
405                         sleep 1
406                         echo "WARNING : mount faild, re-tring"
407                         sleep 1
408                         eval $MOUNT_CMD
409                         if ! is_union_mounted;then
410                                 echo "ERROR: The Union File-system is not mounted !"
411                                 show_mounted_info
412                                 return 1
413                         fi
414                 fi
415         else
416                 echo "WARNING Union already mounted, using it"
417                 show_mounted_info
418         fi
419 }
420
421 cleanups() {
422         #delete folders created by aufs if empty
423         rmdir -rf "${APPDATADIR}/.wh..wh.plnk" 2>/dev/null
424         rmdir -rf "${APPDATADIR}/.wh..wh..tmp" 2>/dev/null
425         rmdir "${APPDATADIR}/.wh..wh.orph" 2>/dev/null
426         rm "${APPDATADIR}/.aufs.xino" 2>/dev/null
427
428         #delete appdata folder and ancestors if _empty_
429         rmdir -p "${APPDATADIR}" 2>/dev/null
430
431         # Clean the loopback device
432         if [ $PND_FSTYPE = ISO ] || [ $PND_FSTYPE = Squashfs ]; then # check if we where running an iso, clean up loop device if we did
433                 LOOP=$(losetup -a | grep "$(basename $PND)" | tail -n1 | awk -F: '{print $1}')
434                 /sbin/losetup -d $LOOP
435                 #rm $LOOP
436         fi
437         losetup -a|cut -d':' -f 1|while read l;do
438                 if ! mount|grep -q $l;then
439                         echo "WARNING Found $l loop as unused. flushing"
440                         /sbin/losetup -d $l
441                 fi
442         done
443
444         echo cleanup done
445 }
446
447 umountPnd() {
448         if is_pnd_mounted;then
449                 PND_WaitFor noMoreProcessPnd "Waiting the PND mount dir to be free"
450                 umount "$PND_MOUNT_DIR/$PND_NAME"
451         fi
452         if is_pnd_mounted; then
453                 echo WARNING umount PND failed, didnt clean up. Process still using this FS :
454                 list_using_fs "$PND_MOUNT_DIR/$PND_NAME"
455                 show_mounted_info
456         else
457                 # removing the now useless mountpoint
458                 if [ -d $PND_MOUNT_DIR/$PND_NAME ];then
459                         rmdir "$PND_MOUNT_DIR/$PND_NAME"
460                 fi
461
462                 # All went well, cleaning
463                 cleanups
464         fi
465 }
466
467 umountUnion() {
468         # Are we root yet ?
469         if [ $(id -u) -ne 0 ];then
470                 sudo /usr/pandora/scripts/pnd_run.sh -u -p "$PND" -b "$PND_NAME"
471                 return $?
472         fi
473
474         # Make sure the Union FS is unmounted
475         #PND_INTERACTIVE=2
476         if is_union_mounted;then
477                 PND_WaitFor noMoreProcessUnion "Waiting the Union to be available"
478                 umount "$UNION_MOUNT_DIR/$PND_NAME" #umount union
479         fi
480         if is_union_mounted; then
481                 echo "WARNING umount UNION failed, didnt clean up. Process still using this FS :"
482                 list_using_fs "$UNION_MOUNT_DIR/$PND_NAME"
483                 show_mounted_info
484         else
485                 # the Union is umounted, removing the now empty mountpoint
486                 if [[ "$PND_MOUNT_DIR" != "$UNION_MOUNT_DIR" ]];then
487                         if [ -d "$UNION_MOUNT_DIR/$PND_NAME" ];then
488                                 rmdir "$UNION_MOUNT_DIR/$PND_NAME"
489                         elif [ -e "$UNION_MOUNT_DIR/$PND_NAME" ];then
490                                 rm "$UNION_MOUNT_DIR/$PND_NAME" >/dev/null 2>&1 # as it might be a symlink
491                         fi
492                 fi
493                 # Try umounting the PND
494                 umountPnd
495         fi
496 }
497
498
499
500 #=============================================================================
501 # Create the condition to run an app, run it and wait for it's end
502 runApp() {
503         cd "$UNION_MOUNT_DIR/$PND_NAME"         # cd to union mount
504         if [ "$STARTDIR" ] && [ -d "$STARTDIR" ]; then
505                 cd "$STARTDIR";                 # cd to folder specified by the optional arg -s
506         fi
507
508         if [ -d $UNION_MOUNT_DIR/$PND_NAME/lib ];then
509                 export LD_LIBRARY_PATH="$UNION_MOUNT_DIR/$PND_NAME/lib:${LD_LIBRARY_PATH:-"/usr/lib:/lib"}"
510         else
511                 export LD_LIBRARY_PATH="$UNION_MOUNT_DIR/$PND_NAME:${LD_LIBRARY_PATH:-"/usr/lib:/lib"}"
512         fi
513
514         if [ -d $UNION_MOUNT_DIR/$PND_NAME/bin ];then
515                 export PATH="$UNION_MOUNT_DIR/$PND_NAME/bin:${PATH:-"/usr/bin:/bin:/usr/local/bin"}"
516         fi
517
518         if [ -d $UNION_MOUNT_DIR/$PND_NAME/share ];then
519                 export XDG_DATA_DIRS="$UNION_MOUNT_DIR/$PND_NAME/share:$XDG_DATA_DIRS:/usr/share"
520         fi
521
522         export XDG_CONFIG_HOME="$UNION_MOUNT_DIR/$PND_NAME"
523
524         "./$EXENAME" $ARGUMENTS
525         RC=$?
526
527         #the app could have exited now, OR it went into bg, we still need to wait in that case till it really quits!
528         PID=$(pidof -o %PPID -x \"$EXENAME\")   # get pid of app
529         while [ "$PID" ];do                     # wait till we get no pid back for tha app, again a bit ugly, but it works
530                 sleep 10s
531                 PID=`pidof -o %PPID -x \"$EXENAME\"`
532         done
533         return $RC
534 }
535
536
537 main() {
538         case $ACTION in
539         mount)  
540                 mountUnion
541                 ;;
542         umount)
543                 umountUnion
544                 ;;
545         run)
546                 PND_BeginTask "Mount the PND"
547                 mountUnion
548                 PND_EndTask
549                 if [ $? -ne 0 ];then
550                         zenity --warning --title="Mounting the PND failed" --text="Mounting the PND failed. The application wont start. Please have a look at $PND_LOG"
551                         return 3
552                 fi
553                 if [ -e /proc/pandora/cpu_mhz_max ] && [ ! -z "$PND_CPUSPEED" ];then
554                         PND_BeginTask "Set CPU speed"
555                         PND_setCPUSpeed
556                         PND_EndTask
557                 fi
558                 if [ $CLOSE_X ]; then
559                         PND_BeginTask "Closing X"
560                         PND_CloseX
561                         PND_EndTask
562                 fi
563                 oPWD=$(pwd)
564                 if [ -e "${APPDATADIR}/PND_pre_script.sh" ]; then
565                         PND_BeginTask "Starting user configured pre-script"
566                         . ${APPDATADIR}/PND_pre_script.sh # Sourcing so it can shared vars with post-script ;)
567                         PND_EndTask
568                 fi
569                 PND_BeginTask "Starting the application ($EXENAME $ARGUMENTS)"
570                 runApp
571                 PND_EndTask
572                 if [ -e "${APPDATADIR}/PND_post_script.sh" ]; then
573                         PND_BeginTask "Starting user configured post-script"
574                         . ${APPDATADIR}/PND_post_script.sh
575                         PND_EndTask
576                 fi
577                 cd $oPWD
578                 if [ $CLOSE_X ]; then
579                         PND_BeginTask "Restarting X"
580                         PND_RestartX
581                         PND_EndTask
582                 fi
583                 if [ ! -z "$CURRENTSPEED" ]; then
584                         PND_BeginTask "Reset CPU speed to $CURRENTSPEED"
585                         PND_resetCPUSpeed
586                         PND_EndTask
587                 fi
588                 PND_BeginTask "uMount the PND"
589                 umountUnion
590                 PND_EndTask
591                 ;;
592         esac
593 }
594
595 ######################################################################################
596 ####    Parsing the arguments :
597 ##
598 ACTION=run
599 while [ "$#" -gt 0 ];do
600         if [ "$#" -gt 1 ] && ( [[ "$(echo $2|cut -c 1)" != "-" ]] || [[ "$1" = "-a" ]] );then
601                 case "$1" in
602                 -p) PND="$2";;
603                 -e) EXENAME="$2";;
604                 -b) PND_NAME="$2";;
605                 -s) STARTDIR="$2";;
606                 -j) append="$2";;
607                 -c) PND_CPUSPEED="$2";;
608                 -d) APPDATASET=1;APPDATADIR="$2";;
609                 -a) ARGUMENTS="$2";;
610                 *)      echo "ERROR while parsing arguments: \"$1 $2\" is not a valid argument"; 
611                         echo "Arguments were : $PND_ARGS"
612                         showHelp;
613                         exit 1 ;;
614                 esac
615                 shift 2
616         else # there's no $2 or it's an argument
617                 case "$1" in
618                 -m) ACTION=mount;;
619                 -u) ACTION=umount;;
620                 -x) CLOSE_X=1;;
621                 -d) APPDATASET=1;;
622                 *)      echo "ERROR while parsing arguments: \"$1\" is not a valid argument"; 
623                         echo "Arguments were : $PND_ARGS"
624                         showHelp;
625                         exit 1 ;;
626                 esac
627                 shift
628
629         fi
630 done
631
632 #PND_NAME really should be something sensible and somewhat unique
633 #if -b is set use that as pnd_name, else generate it from PND
634 #get basename (strip extension if file) for union mountpoints etc, maybe  this should be changed to something specified inside the xml
635 #this should probably be changed to .... something more sensible
636 #currently only everything up to the first '.' inside the filenames is used.
637 PND_NAME=${PND_NAME:-"$(basename $PND | cut -d'.' -f1)"}
638
639 PND_LOG="/tmp/pndrun_${PND_NAME}.out"
640 PND_HEADER="PND PND_FSTYPE APPDATADIR APPDD_FSTYPE PND_CPUSPEED EXENAME ARGUMENTS"
641
642 if [ ! -e "$PND" ]; then #check if theres a pnd suplied, need to clean that up a bit more
643         echo "ERROR: selected PND($PND) file does not exist!"
644         showHelp
645         exit 1
646 fi
647
648 if [ ! "$EXENAME" ] && [[ "$ACTION" = "run" ]]; then
649         echo "ERROR: no executable name provided!"
650         showHelp
651         exit 1
652 fi
653
654 PND_FSTYPE=$(file -b "$PND" | awk '{ print $1 }')       # is -p a zip/iso or folder?
655 MOUNTPOINT=$(df "$PND" | tail -1|awk '{print $6}')      # find out on which mountpoint the pnd is
656 if [ $(df "$PND"|wc -l) -eq 1 ];then                    # this is actually a bug in busybox
657         MOUNTPOINT="/";
658 elif [ ! -d "$MOUNTPOINT" ]; then 
659         MOUNTPOINT="";
660 fi
661 [ ! -z $APPDATASET ] || [ -z ${MOUNTPOINT} ] && APPDATADIR=${APPDATADIR:-$(dirname $PND)/$PND_NAME}
662 APPDATADIR=${APPDATADIR:-${MOUNTPOINT}/pandora/appdata/${PND_NAME}}
663 APPDD_FSTYPE=$(mount|awk '$3=="'${MOUNTPOINT}'"{print $5}')
664 CPUSPEED_FILE=${MOUNTPOINT}/pandora/appdata/${PND_NAME}/cpuspeed
665 if [ -f "$CPUSPEED_FILE" ]; then
666         PND_CPUSPEED=$(cat "$CPUSPEED_FILE")
667 fi
668 export APPDATADIR PND PND_NAME
669
670 #Only logging when running
671 if [[ "$ACTION" == "run" ]];then
672         PND_Start
673         {
674         if [ $CLOSE_X ]; then
675                 main 2>&1 & 
676                 disown
677         else
678                 main 2>&1
679         fi
680         }>>$PND_LOG
681         PND_Stop
682 else
683         main
684 fi