#!/bin/sh -e

patch=debian/patches/point-to-right-place.patch
if ! quilt pop -a; then
   quilt applied && { echo "failed to pop"; exit 1; }
fi

quilt delete "${patch##*/}"
quilt new "${patch##*/}"
quilt header -r <<EOF
Description: set install path in launcher scripts
 This patch is generated using debian/${0##*/}
Origin: Scott Moser <smoser@ubuntu.com>
Forwarded: not-needed
Last-Update: $(date "+%Y-%m-%d")
EOF

for x in bin/*; do
  cmd=${x#bin/}
  case "$cmd" in
    ec2-ami-tools-version) rb=showversion;;
    ec2-bundle-image) rb=bundleimage;;
    ec2-bundle-vol) rb=bundlevol;;
    ec2-delete-bundle) rb=deletebundle;;
    ec2-download-bundle) rb=downloadbundle;;
    ec2-migrate-bundle) rb=migratebundle;;
    ec2-migrate-manifest) rb=migratemanifest;;
    ec2-unbundle) rb=unbundle;;
    ec2-upload-bundle) rb=uploadbundle;;
    *) echo "unknown command $cmd"; exit 1;;
  esac
  quilt add "$x"
  cat > "$x" <<EOF
#!/bin/bash
home="\${EC2_AMITOOL_HOME:-@@EC2_AMITOOL_HOME@@}"
[ "\${home#@@}" = "\${home}" ] ||
   { echo "you must either set EC2_AMITOOL_HOME or install" 1>&2; exit 1; }
exec -a "\${0##*/}" ruby -I "\${home}/lib" \\
   "\$home/lib/ec2/amitools/$rb.rb" "\$@"
EOF
done

quilt refresh
quilt pop
