#!/bin/bash
#
# build_installer.sh
#
# This script is part of the tutorial about "How to Install
# an iPhone Web Application". The script is run with a
# single argument, the application name, which defaults to
# rg_rotate for the purposes of the tutorial.
# 
# The script demonstrates how to build a web page which can
# be used to provision an iPhone web application. The
# source file for the web application is expected to be named
# [application_name].html and the provisioning web page is
# written out as [application_name]_installer.html.
# 
# This script can be enhanced with prompts for additional
# resource files and mime types. Alternatively, additional
# resources can be hand coded where indicated.
# 
# The body of the provisioning web page holds the complete,
# encoded web application within a link that can be selected
# in the Mobile Safari browser. When this link is selected,
# the data URL that encodes the web application is placed
# in Safari's URL Bar. At this point the application can be
# installed with the + key of the Safari Button Bar. In order
# for Safari to access the provisioning web page, it must
# be placed on a preferably local web server that can be
# reached by the iPhone.
#
# The provisioning web page is generated to be run as a mini
# iPhone application itself. For example, it will respond to
# orientation changes and hides the URL Bar when loaded.
# 
# Copyright (c) 2008 Technetra Corp
# 
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
##############################################################
#
# BEGIN RESOURCE MAPPINGS
# change the following dummy resource mappings as needed:
# Specifically, for each N define the mapping in this file
# as: mime_type[N]='type/subtype'; resource_file[N]='file_path'
# and the label RESOURCE_N as the corresponding URL reference
# in the web application file.
# E.g., mime_type[1]='image/jpg'; resource_file[1]='myface.jpg'
# and <img src="RESOURCE_1" alt="myface" /> in the web
# application file.
mime_type[1]='image/gif'; resource_file[1]='/dev/null'
mime_type[2]='image/gif'; resource_file[2]='/dev/null'
mime_type[3]='image/gif'; resource_file[3]='/dev/null'
# END RESOURCE MAPPINGS
MAX_RESOURCES=${#mime_type[*]} 
map_resource() {
 local ret=$1
 local id=$2 
 local resource='s~RESOURCE_${id}~data:'${mime_type[$id]}'\;base64,'`$BASE64 -w 0 ${resource_file[$id]}`'~\;'
 eval "$ret=$resource"
}
BASE64="/usr/bin/env base64"
XARGS="/usr/bin/env xargs"
TEMPFILE="/usr/bin/env tempfile"
application=${1:-rg_rotate}
touch_icon_image_file="${application}_touch_icon.png"
if [[ ! -e "${application}.html" ]]; then
  echo "Template web application file ${application}.html does not exist, please create and run application installer again -- exiting"
  exit
fi
read -p "Enter location of apple-touch-icon image file (./$touch_icon_image_file): " ipath
[[ "$ipath" ]] && touch_icon_image_file="$ipath"
if [[ ! -e "$touch_icon_image_file" ]]; then
  echo "$touch_icon_image_file does not exist, will create application with empty bookmark icon"
  touch_icon_image_file=/dev/null
fi
echo "Using ${application}.html as input template for web application"
touch_icon_mime_type="image/${touch_icon_image_file##*.}"
TFILE=`$TEMPFILE`
trap "rm -f $TFILE" 0 1 2 5 15
# TODO: hand code or prompt for additional resources
additional_resources_map=
for i in $(seq 1 $MAX_RESOURCES); do
  map_resource res $i
  additional_resources_map="$additional_resources_map$res"
done
cat <<EOM1 | $XARGS -I{} sed -e {} ${application}.html > $TFILE
's~TOUCH_ICON~data:'$touch_icon_mime_type';base64,'`$BASE64 -w 0 $touch_icon_image_file`'~; \
 $additional_resources_map \
'
EOM1
echo -e "Creating `pwd`/${application}_installer.html\nPoint Mobile Safari to the HTTP location of this file to install ${application}"
#
# Provisioning web page:
cat <<EOM2 > ${application}_installer.html
<html>
  <head>
    <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
    <style>
        body[orient="portrait"] {
          height: 460px;
        }
        body[orient="landscape"] {
          height: 300px;
        }
    </style>
    <script>
      var currentWidth = 0;
      addEventListener("load", function() {
          setTimeout(orientationChange, 0);
      }, false);
      function orientationChange() {
          if (window.innerWidth != currentWidth) {
              currentWidth = window.innerWidth;
              document.body.setAttribute('orient', (currentWidth == 320) ? "portrait" : "landscape");
              setTimeout(scrollTo, 100, 0, 1);
          }
      }
      setInterval(orientationChange, 400);
    </script>
  </head>
  <body style="background-color: #d0d0d0; font-size: 24px; height: 460px;">
      <h2 style="text-align: center;"><span style="background-color: #000; color: #fff;">"${application}"</span><br />Installation Steps</h2>
      <ol>
          <li>Select <a style="background-color: #ff0; font-weight: bold;" href="data:text/html;charset=utf-8;base64,`$BASE64 $TFILE`">this link</a> to install "${application}" as a data URL in the URL Bar, then</li>
          <li>Press <span style="background-color: #ff0; font-weight: bold;">+</span> key on iPhone button bar to add "${application}" to home page.</li>
      </ul>
  </body>
</html>
EOM2

