#!/bin/sh

: ${aicontact:=scripts@mit.edu}
: ${aimaintainer:=scripts.mit.edu}
: ${ailocker:=scripts}


checkfailed() {
  if [ -f "$lroot/web_scripts/$addrend/.failed" ]; then
    rm -f "$lroot/web_scripts/$addrend/.failed"
    exit 1
  fi
}

die() {
  echo "== INSTALLATION FAILED =="
  echo "Sorry, the installation failed:"
  echo "$@"
  echo "Please contact $aicontact and provide a copy of the output of this installer."
  exit 1
}

attach scripts
[ "$ailocker" != "scripts" ] && attach "$ailocker"

sshrun() {
  /afs/athena.mit.edu/contrib/scripts/bin$scriptsdev/scripts-ssh "$lname" "$@" 2>/dev/null
}

vsshrun() {
  /afs/athena.mit.edu/contrib/scripts/bin$scriptsdev/scripts-ssh "$lname" "$@"
}

checksqlpass() {
    errors=`sshrun "/mit/scripts/sql/bin$scriptsdev/test-password"`
    if [ "$errors" != "" ]; then
        if [ "$1" -eq 1 ]; then
          rm -f "$lroot/.sql/my.cnf"
        fi
        echo
        echo "ERROR:"
        printf "$2"
        exit
    fi
}

override=1
if [ "$override" = "" ]; then
echo "The $aimaintainer automatic installers are currently unavailable."
echo "We hope to make them available again soon."
echo "If you would like us to notify you as soon as they are available again,"
echo "let us know by sending us an e-mail at $aicontact"
exit 
fi

echo 
echo "== Welcome to the $aimaintainer installer for $sname =="
echo

echo "For documentation, including a link to the Athena rules of use,"
echo "see <http://scripts.mit.edu/start>."
echo
echo "Please report problems with this installer to $aicontact."
echo
echo "Are you performing this install for:"
echo "1. Your personal Athena account"
echo "2. A locker that you control (a club, a course, etc)"
echo "If you do not understand this question, you should answer '1'."
printf "Please enter either '1' or '2' (without quotes): "
read whofor
if [ "$whofor" = 1 ]; then
    lname="${ATHENA_USER:-$USER}"
elif [ "$whofor" = 2 ]; then
    echo
    echo "OK.  $sname will be installed into a locker of your choice that"
    echo "you control.  Please enter the name of the selected locker below."
    echo "(For the locker /mit/lsc -- which has a full path of"
    echo "/afs/athena.mit.edu/activity/l/lsc -- you would simply enter lsc)."
    printf "Locker name: "
    read lname
else
    echo
    echo "ERROR:"
    echo "You must select either '1' or '2'."
    exit 1
fi
while true; do
    if attach "$lname"; then
        break
    fi
    echo "$lname is not a valid locker name."
    printf "Locker name: "
    read lname
done
lroot="/mit/$lname" 

echo
echo Checking the status of your scripts.mit.edu account...

attach scripts 2>/dev/null
. "/mit/scripts/bin$scriptsdev/signup-web"

echo
echo "Your new copy of $sname will appear on the web at a URL"
echo "that starts with http://$lname.scripts.mit.edu/"
echo "Please decide upon a complete URL and enter it below."
echo "You must enter one or more characters after mit.edu/"
echo "The completed address must only contain a-z, 0-9, and /."
printf "Desired address: http://$lname.scripts.mit.edu/"
read addrend

addrend=`perl -0e 'print $ARGV[0] =~ /^([\w\/-]*[\w-])\/*$/' -- "$addrend"`
if [ "$addrend" = "" ]; then
	echo
	echo "ERROR:"
	echo "You must enter one or more characters after mit.edu/"
	echo "The completed address must only contain a-z, 0-9, and /."
	exit 1
fi

if [ -d "$lroot/web_scripts/$addrend" ]; then
    echo
    echo "ERROR:"
    echo "You already have a directory corresponding to that web address."
    echo "Please remove that directory, choose a different address, or"
    echo "contact $aicontact for assistance."
    exit 1
fi

if [ "$requires_sql" = "" ]; then
  requires_sql=1
fi

if [ ! -f "$lroot/.my.cnf" ]; then
  mkdir "$lroot/.sql" 2>/dev/null
  fs sa "$lroot/.sql" daemon.scripts write
  fs sa "$lroot/.sql" daemon.sql write
  ln -nfs "$lroot/.sql/my.cnf" "$lroot/.my.cnf" 2>/dev/null
fi

fs sa "$lroot/.sql" system:anyuser none
fs sa "$lroot/.sql" system:authuser none

if [ "$requires_sql" -eq 1 ]; then
  sqlinfo=`sshrun "/mit/scripts/sql/bin$scriptsdev/get-password"`
  if [ "$sqlinfo" = "" ]; then
      echo 
      echo "You already have a MySQL account but you do not have a .my.cnf file."
      echo "If you do not remember your MySQL account password, you can change it"
      echo "at http://sql.mit.edu using MIT certificates."
      printf "Please type your MySQL password and press [enter]: "
      stty -echo
      read sqlpass
      stty echo
      echo
      sqlhost="sql.mit.edu"
      sqluser=$lname
      . "/mit/scripts/sql/bin$scriptsdev/save-password"
      checksqlpass 1 'The MySQL password that you typed appears to be incorrect.\n'
      echo
      echo "OK.  Continuing with the install..."
  else
      checksqlpass 0 'The MySQL login information in your .my.cnf file\nappears to be incorrect.\n'
  fi
fi

origdir=`pwd`
mkdir -p "$lroot/web_scripts_tmp"
cd "$lroot/web_scripts_tmp"
fs sa . system:anyuser none
fs sa . system:authuser none
fs sa . daemon.scripts write
fs sa . system:scripts-security-upd write
echo "This directory is necessary to store login sessions and other transient files for auto-installed packages from scripts.mit.edu." > DO_NOT_DELETE.txt
mkdir -p "$lroot/web_scripts/$addrend"
cd "$lroot/web_scripts/$addrend"
fs sa . system:anyuser none
fs sa . system:authuser none
fs sa . daemon.scripts write
fs sa . system:scripts-security-upd write

# This version is deprecated, use create_scripts_dir instead

if [ "$create_dir" = "" ]; then
  create_dir=0
fi

if [ "$create_dir" -eq 1 ]; then
  mkdir -p "$lroot/scripts-$deploy"
  fs sa "$lroot/scripts-$deploy" system:anyuser none
  fs sa "$lroot/scripts-$deploy" system:authuser none
  fs sa "$lroot/scripts-$deploy" daemon.scripts write
  fs sa "$lroot/scripts-$deploy" system:scripts-security-upd write
fi

# This is the better version

if [ "$create_scripts_dir" = "" ]; then
  create_scripts_dir=0
fi

if [ "$create_scripts_dir" -eq 1 ]; then
  mkdir -p "$lroot/Scripts/$deploy"
  fs sa "$lroot/Scripts/$deploy" system:anyuser none
  fs sa "$lroot/Scripts/$deploy" system:authuser none
  fs sa "$lroot/Scripts/$deploy" daemon.scripts write
  fs sa "$lroot/Scripts/$deploy" system:scripts-security-upd write
fi

if [ "$wizard" != "" ]; then
  vsshrun "/mit/$ailocker/wizard/bin/wizard" "install" "$@" "$wizard" "$lroot/web_scripts/$addrend"
  exit 0
fi

if [ "$prompt_username" = "" ]; then
  admin_username="admin"
  prompt_username=0
fi
if [ "$prompt_password" = "" ]; then
  prompt_password=1
fi

if [ "$prompt_username" -eq 1 ]; then
    echo
    echo "You will be able to log in to $sname using a username of your choice."
    echo "Please decide upon a username and enter it below."
    echo "Your username must contain only alphanumeric characters (a-z, 0-9)."
    printf "Desired username: "
    read admin_username
    admin_username=`perl -0e 'print $ARGV[0] =~ /^([[:alnum:]]+)$/' -- "$admin_username"`
    if [ "$admin_username" = "" ]; then
        echo
        echo ERROR:
        echo "Your username must contain only alphanumeric characters (a-z, 0-9)."
        echo "You will need to run the installer again and choose a different username."
        exit 1
    fi
fi

if [ "$prompt_password" -eq 1 ]; then
    stty -echo
    sshrun "/mit/$ailocker/deploy$scriptsdev/bin/prompt-password" "$sname" "$deploy" "$addrend" "$admin_username"
    stty echo
fi

echo
echo "Unpacking $sname... (this step might take several minutes)"
# xavid: use p to keep the same permissions as in the file
athrun scripts gtar zxpf "/mit/$ailocker/deploy$scriptsdev/$deploy.tar.gz"
files=`athrun scripts gfind . -mindepth 1 -maxdepth 1 | grep -v .admin`
numfiles=`echo "$files" | wc -l`
if [ ! -z "$files" ]; then
    if [ "$numfiles" -eq 1 ]; then
        athrun scripts gfind . -mindepth 2 -maxdepth 2 | xargs -i mv \{} .
        rmdir "$files"
    fi
fi
if [ -f "/mit/$ailocker/deploy$scriptsdev/php.ini/$deploy" ]; then
        nodot=`echo "$lname" | sed "/\./s///"`;
        sed -e "/SCRIPTS_USER/ s//$lname/" -e "/SCRIPTS_NODOT/ s//$nodot/" "/mit/$ailocker/deploy$scriptsdev/php.ini/$deploy" > php.ini
        athrun scripts gfind . -mindepth 1 -type d -exec sh -c 'ln -sf "`echo "$1" | sed '\''s,[^/],,g; s,/,../,g'\''`php.ini" "$1/"' -- {} \;
fi
cd "$origdir"

vsshrun "/mit/$ailocker/deploy$scriptsdev/bin/$deploy" "$sname" "$deploy" "$addrend" "$admin_username" "$requires_sql" "$scriptsdev" "${ATHENA_USER:-$USER}" || die "Unknown failure during configuration"
rm -f "$lroot/web_scripts/$addrend/.scripts-tmp"
checkfailed

echo
echo "== Installation complete! =="
echo "You should now be able to access your new copy of $sname at"
echo "http://$lname.scripts.mit.edu/$addrend/"
echo "(You can replace the http with https if you want to use encryption)"
echo "If you have trouble accessing it, feel free to contact"
echo "the $aimaintainer team by e-mailing $aicontact"
exit 0
