caa75989508a311554a4f00f387ea5f7cb4bad8c
[pandora-libraries.git] / testdata / scripts / pnd_run.sh
1 #!/bin/bash
2  
3 #Usage: pnd_run.sh -p your.pnd -e executeable [-a "(arguments)"] [ -s "cd to folder inside pnd"] [-b UID (name of mountpoint/pandora/appdata)] [-x close x before launching(script needs to be started with nohup for this to work]
4 # -s startdir
5 # arguments can be inside -e, -a is optional
6  
7 #/etc/sudoers needs to be adjusted if you touch any of the sudo lines
8  
9 # look at the comments in the nox part, adjust 
10 #use "lsof /usr/lib/libX11.so.6 | awk '{print $1}'| sort | uniq > whitelist" with nothing running to generate the whitelist
11  
12 #todo - no proper order
13 #validate params better
14 #make uid/pnd_name mandatory (and rename var, its confusing!)
15 #find a clean way of shutting down x without a fixed dm, mabye avoid nohup usage somehow
16 #add options to just mount iso without union and to mount the union later
17 #cleanup
18 #Rewrite! - this sucks
19
20 showHelp() {
21         cat <<endHELP
22 Usage: pnd_run.sh -p your.pnd -e executeable [-a "(arguments)"] [ -s "cd to folder inside pnd"] [-b UID (name of mountpoint/pandora/appdata)] [-x close x before launching(script needs to be started with nohup for this to work]
23 Usage for mounting/umounting pnd_run.sh -p your.pnd -b uid -m or -u
24 endHELP
25 }
26
27 list_using_fs() {
28         for p in $(fuser -m $1 2>/dev/null);do ps hf $p;done
29 }
30
31 runApp() {
32         cd "/mnt/utmp/$PND_NAME"                # cd to union mount
33         if [ "$STARTDIR" ] && [ -d "$STARTDIR" ]; then
34                 cd "$STARTDIR";                 # cd to folder specified by the optional arg -s
35         fi
36         echo "[------------------------------]{ App start }[---------------------------------]"
37         LD_LIBRARY_PATH="/mnt/utmp/$PND_NAME" "./$EXENAME" $ARGUMENTS 
38                                                 # execute app with ld_lib_path set to the union mount, a bit evil but i think its a good solution
39
40         #the app could have exited now, OR it went into bg, we still need to wait in that case till it really quits!
41         PID=$(pidof -o %PPID -x \"$EXENAME\")   # get pid of app
42         while [ "$PID" ];do                     # wait till we get no pid back for tha app, again a bit ugly, but it works
43                 sleep 10s
44                 PID=`pidof -o %PPID -x \"$EXENAME\"`
45         done
46         echo "[-------------------------------]{ App end }[----------------------------------]"
47 }
48
49 mountPnd() {
50         #create mountpoints, check if they exist already first to avoid annoying error messages
51         if ! [ -d "/mnt/pnd/${PND_NAME}" ]; then 
52                 sudo mkdir -p "/mnt/pnd/${PND_NAME}"            #mountpoint for iso, ro
53         fi 
54         #writeable dir for union
55         if ! [ -d "${MOUNTPOINT}/pandora/appdata/${PND_NAME}" ]; then 
56                 sudo mkdir -p "${MOUNTPOINT}/pandora/appdata/${PND_NAME}"
57                 sudo chmod -R a+xrw "${MOUNTPOINT}/pandora/appdata/${PND_NAME}" 2>/dev/null
58         fi
59         if ! [ -d "/mnt/utmp/${PND_NAME}" ]; then
60                 sudo mkdir -p "/mnt/utmp/${PND_NAME}"           # union over the two
61         fi
62         rm  /tmp/cpuspeed
63         if [ ${cpuspeed:-$(cat /proc/pandora/cpu_mhz_max)} -gt $(cat /proc/pandora/cpu_mhz_max) ]; then 
64            cpuselection=$(zenity --title="set cpu speed" --height=240 --list --column "id" --column "Please select" --hide-column=1 --text="$PND_NAME suggests to set the cpu speed to $cpuspeed MHz to make it run properly.\n\n Do you want to change the cpu speed? (current speed: $(cat /proc/pandora/cpu_mhz_max) MHz)" "yes" "Yes, set it to that value" "custom" "Yes, select custom value" "no" "No, don't change the speed")
65           if [ ${cpuselection} = "yes" ]; then  
66                 cat /proc/pandora/cpu_mhz_max > /tmp/cpuspeed   
67                 sudo /usr/pandora/scripts/op_cpuspeed.sh $cpuspeed
68           elif [ ${cpuselection} = "custom" ]; then     
69                 cat /proc/pandora/cpu_mhz_max > /tmp/cpuspeed           
70                 sudo /usr/pandora/scripts/op_cpuspeed.sh
71         fi
72         #gksudo --message ", enter your password to allow" "echo $cpuspeed>/proc/pandora/cpu_mhz_max"
73         fi
74
75         #is the union already mounted? if not mount evrything, else launch the stuff
76         mount | grep "on /mnt/utmp/${PND_NAME} type"
77         if [ $? -ne 0 ];then
78                 echo not mounted on loop yet, doing so
79                 #check if pnd is already attached to loop 
80                 LOOP=$(sudo losetup -a | grep "$PND" | tail -n1 | awk -F: '{print $1}')
81                 #check if the loop device is already mounted
82                 if ! [ -z "$LOOP" ];then
83                         loopmountedon=$( mount | grep "$(mount | grep "$LOOP" | awk '{print $3}')" | grep utmp | awk '{print $3}' )
84                 else
85                         loopmountedon=""
86                 fi
87                 echo "LoopMountedon: $loopmountedon"
88                 if [ ! "$loopmountedon" ]; then #check if the pnd is already attached to some loop device but not used
89                         FREELOOP=$LOOP 
90                         #reuse existing loop
91                         if [ ! "$LOOP" ]; then
92                                 FREELOOP=$(sudo /sbin/losetup -f) #get first free loop device
93                                 echo $FREELOOP
94                                 if [ ! "$FREELOOP" ]; then  # no free loop device, create a new one
95                                             #find a free loop device and use it 
96                                             usedminor=$(sudo /sbin/losetup -a | tail -n1)
97                                             usedminor=${usedminor:9:1}
98                                             echo usedminor $usedminor
99                                             freeminor=$(($usedminor+1))
100                                             echo freeminor $freeminor
101                                             sudo mknod -m777 /dev/loop$freeminor b 7 $freeminor
102                                             FREELOOP=/dev/loop$freeminor
103                                 fi
104                         fi
105                         #detect fs
106
107                         case $PND_FSTYPE in
108                         ISO)
109                                 sudo /sbin/losetup $FREELOOP "$PND" #attach the pnd to the loop device
110                                 mntline="sudo mount ${FREELOOP}" #setup the mountline for later
111                                 #mntline="sudo mount -o loop,mode=777 $PND /mnt/pnd/$PND_NAME"
112                                 echo "Filetype is $PND_FSTYPE";;
113                         directory)
114                                 #we bind the folder, now it can be treated in a unified way 
115                                 #ATENTION: -o ro doesnt work for --bind at least on 25, on 26 its possible using remount, may have changed on 27
116                                 mntline="sudo mount --bind -o ro \"${PND}\" "
117                                 echo "Filetype is $PND_FSTYPE";;
118                         Squashfs)
119                                 sudo /sbin/losetup $FREELOOP "$PND" #attach the pnd to the loop device
120                                 mntline="sudo mount -t squashfs  ${FREELOOP}"
121                                 echo "Filetype is $PND_FSTYPE";;
122                         *)
123                                 echo "error determining fs, output was $PND_FSTYPE"
124                                 exit 1;;
125                         esac
126
127                         echo "$mntline"
128                         $mntline "/mnt/pnd/${PND_NAME}" #mount the pnd/folder
129                         echo "mounting union!"
130                         FILESYSTEM=$(mount | grep "on $MOUNTPOINT " | grep -v rootfs | awk '{print $5}' | tail -n1) #get filesystem appdata is on to determine aufs options
131                         echo "Filesystem is $FILESYSTEM"
132                         if [[ "$FILESYSTEM" = "vfat" ]]; then # use noplink on fat, dont on other fs's 
133                                 #append is fucking dirty, need to clean that up
134                                 sudo mount -t aufs -o exec,noplink,dirs="$MOUNTPOINT/pandora/appdata/$PND_NAME=rw+nolwh":"/mnt/pnd/$PND_NAME=rr$append" none "/mnt/utmp/$PND_NAME"
135                                 # put union on top
136                         else
137                                 sudo mount -t aufs -o exec,dirs="$MOUNTPOINT/pandora/appdata/$PND_NAME=rw+nolwh":"/mnt/pnd/$PND_NAME=rr$append" none "/mnt/utmp/$PND_NAME" 
138                                 # put union on top
139                         fi
140                 else #the pnd is already mounted but a mount was requested with a different basename/uid, just link it there
141                               echo $LOOP already mounted on $loopmountedon skipping losetup - putting link to old mount
142                               #this is bullshit
143                               sudo rmdir "/mnt/utmp/$PND_NAME"
144                               sudo ln -s $loopmountedon "/mnt/utmp/$PND_NAME" 
145                 fi
146         
147         else
148                 echo "Union already mounted"
149         fi
150 }
151
152 unmountPnd() {
153         sudo umount "/mnt/utmp/$PND_NAME" #umount union
154         if [ -f /tmp/cpuspeed ]; then
155                 cpuspeed=$(cat /tmp/cpuspeed)
156                 sudo /usr/pandora/scripts/op_cpuspeed.sh $cpuspeed
157                 rm /tmp/cpuspeed
158         fi
159         if [ -z "$(mount |grep utmp/$PND_NAME|cut -f3 -d' ')" ]; then
160                 # check if the umount was successfull, if it wasnt it would mean that theres still something running so we skip this stuff, 
161                 # this WILL lead to clutter if it happens, so we should make damn sure it never happens
162                 # umount the actual pnd
163                 sudo umount "/mnt/pnd/$PND_NAME"
164                 if [ -z "$(mount |grep pnd/$PND_NAME|cut -f3 -d' ')" ]; then
165                         #delete folders created by aufs if empty
166                         sudo rmdir "$MOUNTPOINT/pandora/appdata/$PND_NAME/.wh..wh.plnk" 2>/dev/null
167                         sudo rmdir "$MOUNTPOINT/pandora/appdata/$PND_NAME/.wh..wh..tmp" 2>/dev/null
168                         #delete appdata folder and ancestors if empty
169                         sudo rmdir -p "$MOUNTPOINT/pandora/appdata/$PND_NAME/" 2>/dev/null
170                         #delete tmp mountpoint
171                         if [ -d "/mnt/utmp/$PND_NAME" ];then
172                                 sudo rmdir "/mnt/utmp/$PND_NAME"
173                         else
174                                 sudo rm "/mnt/utmp/$PND_NAME" >/dev/null 2>&1
175                         fi
176                         if [ $PND_FSTYPE = ISO ] || [ $PND_FSTYPE = Squashfs ]; then # check if we where running an iso, clean up loop device if we did
177                                 LOOP=$(sudo losetup -a | grep "$(basename $PND)" | tail -n1 | awk -F: '{print $1}')
178                                 sudo /sbin/losetup -d $LOOP
179                                 sudo rm $LOOP
180                         fi
181                         if [ -d /mnt/pnd/$PND_NAME ];then
182                                 sudo rmdir "/mnt/pnd/$PND_NAME" #delete pnd mountpoint
183                         fi
184
185                         echo cleanup done
186                 else
187                         echo umount failed, didnt clean up. Process still using this FS :
188                         list_using_fs "/mnt/pnd/$PND_NAME"
189                 fi
190         else
191                 echo umount failed, didnt clean up. Process still using this FS :
192                 list_using_fs "/mnt/utmp/$PND_NAME"
193         fi
194 }
195
196 main() {
197         if [ $nox ]; then #the app doesnt want x to run, so we kill it and restart it once the app quits
198                 if [ ! $(pidof X) ]; then 
199                         unset $nox
200                 else
201                         applist=$(lsof /usr/lib/libX11.so.6 | awk '{print $1}'| sort | uniq)
202                         whitelist=$(cat ~/pndtest/whitelist) #adjust this to a fixed whitelist, maybe in the config dir
203                         filteredlist=$(echo -e "$applist\n\n$whitelist\n\n$whitelist" | sort | uniq -u) #whitelist appended two times so those items are always removed
204                         if [ ${#filteredlist} -ge 1 ]; then
205                                 message=$(echo -e "The following applications are still running, are you sure you want to close x? \n$filteredlist")
206                                 echo -e "?ae[34me[30m?"
207                                 xmessage -center "$message", -buttons yes,no
208                                 if [ $? = 102 ]; then
209                                         exit 1
210                                 fi
211                                 sudo /etc/init.d/slim-init stop
212                                 sleep 5s
213                         else
214                                 echo -e "?ae[34me[30m?"
215                                 xmessage -center "killing x, nothing of value will be lost", -buttons ok,cancel
216                                 if [ $? = 102 ]; then
217                                         exit 1
218                                 fi
219                                 # close x now, do we want to use slim stop or just kill x?
220                                 sudo /etc/init.d/slim-init stop
221                                 sleep 5s
222                         fi
223                 fi
224         fi
225
226         case $ACTION in
227         mount)  mountPnd;;
228         umount) unmountPnd;;
229         run)
230                 mountPnd
231                 oPWD=$(pwd)
232                 runApp
233                 cd $oPWD
234                 unmountPnd;;
235         esac
236
237
238         if [ $nox ]; then #restart x if it was killed
239                 echo "starting x in 5s"
240                 sleep 5
241                 sudo /etc/init.d/slim-init start
242         fi
243 }
244
245 ######################################################################################
246 ####    Parse arguments
247 ##
248
249 TEMP=`getopt -o p:e:a:b:s:m::u::n::x::j:c: -- "$@"`
250  
251 if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
252  
253 # Note the quotes around `$TEMP': they are essential!
254 eval set -- "$TEMP"
255  
256 ACTION=run
257 while true ; do
258         case "$1" in
259                 -p) PND=$2;shift 2;;
260                 -e) EXENAME=$2;shift 2 ;;
261                 -b) PND_NAME=$2;shift 2;;
262                 -s) STARTDIR=$2;shift 2;;
263                 -m) ACTION=mount;shift 2;;
264                 -u) ACTION=umount;shift 2;;
265                 -x) nox=1;shift 2;;
266                 -j) append=$2;shift 2;;
267                 -c) cpuspeed=$2;shift 2;;
268                 -a) 
269                         case "$2" in
270                                 "") echo "no arguments"; shift 2 ;;
271                                 *)  echo "args set to \`$2'" ;ARGUMENTS=$2;shift 2 ;;
272                         esac ;;
273                 --) shift ; break ;;
274                 *) echo "Error while parsing arguments!" ; exit 1 ;;
275         esac
276 done
277 if [ ! -e "$PND" ]; then #check if theres a pnd suplied, need to clean that up a bit more
278         echo "ERROR: selected PND file does not exist!"
279         showHelp
280         exit 1
281 fi
282 if [ ! "$EXENAME" ] && [[ "$ACTION" = "run" ]]; then
283         echo "ERROR: no executable name provided!"
284         showHelp
285         exit 1
286 fi
287
288
289 PND_FSTYPE=$(file -b "$PND" | awk '{ print $1 }')       # is -p a zip/iso or folder?
290 MOUNTPOINT=$(df "$PND" | tail -1|awk '{print $6}')      # find out on which mountpoint the pnd is
291 if [ ! -d "$MOUNTPOINT" ] || [ $MOUNTPOINT = "/" ]; then 
292         MOUNTPOINT="";
293 fi
294  
295 #PND_NAME really should be something sensible and somewhat unique
296 #if -b is set use that as pnd_name, else generate it from PND
297 #get basename (strip extension if file) for union mountpoints etc, maybe  this should be changed to something specified inside the xml
298 #this should probably be changed to .... something more sensible
299 #currently only everything up to the first '.' inside the filenames is used.
300 PND_NAME=${PND_NAME:-"$(basename $PND | cut -d'.' -f1)"}
301
302 if [ $nox ]; then
303         main > "/tmp/pndrun${PND_NAME}_$ACTION.out" 2>&1 & 
304         disown
305 else
306         main > "/tmp/pndrun${PND_NAME}_$ACTION.out" 2>&1
307 fi
308
309