#!/bin/sh

writeUserMessage()
{
  echo $@
  echo $@ >> /a-optis_log
}

writeToFile()
{
  echo "wrote to file $2: '$1'" >> /a-optis_log
  echo $1 >> $2
}

executeOutputCommand() 
{
  echo -e "\\n" >> /a-optis_log
  echo "========================" >> /a-optis_log
  echo "Executing command:" >> /a-optis_log
  echo $@ >> /a-optis_log
  echo "------------------------" >> /a-optis_log
  $@ >> /a-optis_log 2>&1
  echo "========================" >> /a-optis_log
  echo -e "\\n" >> /a-optis_log
}

mount / -o remount,rw

language = 0
while [ "$language" != "1"  ] && [ "$language" != "2" ]; do
  clear
  writeUserMessage "............................................."
  writeUserMessage -e "\\n"
  writeUserMessage "A-OPTIS v0.2a (20/12/09)"
  writeUserMessage -e "\\n"
  writeUserMessage "--> Português (1)"
  writeUserMessage "--> English   (2)"
  writeUserMessage -e "\\n"
  writeUserMessage "Por favor, escolha uma linguagem (introduza '1' ou '2') e prima [ENTER]"
  writeUserMessage "Please select a language (enter '1' or '2') and press [ENTER]:"
  read language
done

installOption = 0
while [ "$installOption" != "1" ] && [ "$installOption" != "2" ] && [ "$installOption" != "3" ]; do
  clear
  if [ "$language" == "1" ]
  then
    writeUserMessage "=============================================================="
    writeUserMessage "== A-OPTIS - Script de instalação do optware no ASUS O!Play =="
    writeUserMessage "== -------------------------------------------------------- =="
    writeUserMessage "==         Versão: 0.2a (testada no firmware 1.17P)         =="
    writeUserMessage "== -------------------------------------------------------- =="
    writeUserMessage "==        20/12/09 » Leogansky » leoxgansky@gmail.com       =="
    writeUserMessage "=============================================================="
    writeUserMessage -e "\\n"
    writeUserMessage "IMPORTANTE: NO CASO DE USAR UM HUB, CERTIFIQUE-SE QUE O DISCO USB QUE USA COMO DISCO DE SISTEMA ESTÁ LIGADO NA PORTA 1 DO MESMO."    
    writeUserMessage -e "\\n"
    writeUserMessage "Escolha uma opção:"
    writeUserMessage "=> (1) - Instalar o sistema optware"
    writeUserMessage "=> (2) - Instalar aplicações optware (necessita do sistema optware já instalado)"
    writeUserMessage "=> (3) - Sair"
    writeUserMessage -e "\\n"
    writeUserMessage "NOTA: O ASUS O!PLAY TEM DE ESTAR LIGADO A UM ROUTER COM ACESSO À INTERNET PARA EFECTUAR O PROCESSO DE INSTALAÇÃO!!!"
    writeUserMessage -e "\\n" 
  else
    writeUserMessage "======================================================="
    writeUserMessage "== A-OPTIS - ASUS O!Play Optware Installation Script =="
    writeUserMessage "== ------------------------------------------------- =="
    writeUserMessage "==     Version: 0.2a (tested on firmware 1.17P)      =="
    writeUserMessage "== ------------------------------------------------- =="
    writeUserMessage "==    20/12/09 » Leogansky » leoxgansky@gmail.com    =="
    writeUserMessage "======================================================="
    writeUserMessage -e "\\n"
    writeUserMessage "IMPORTANT: IF YOU'RE USING A HUB, MAKE SURE THE USB DISK YOU'RE USING AS SYSTEM DISK IS CONNECTED TO PORT 1."    
    writeUserMessage -e "\\n"    
    writeUserMessage "Choose an option:"
    writeUserMessage "=> (1) - Install optware system"
    writeUserMessage "=> (2) - Install optware applications (requires previously installed optware system)"
    writeUserMessage "=> (3) - Exit"
    writeUserMessage -e "\\n"
    writeUserMessage "NOTE: ASUS O!PLAY MUST BE PLUGGED ONTO A ROUTER WITH INTERNET ACCESS IN ORDER TO PROCEED WITH THE INSTALLATION!!!"
    writeUserMessage -e "\\n"
  fi
  read installOption
done

#1 - instalação do optware
if [ "$installOption" == "1" ]
then
  option = 0
  while [ "$option" != "1"  ] && [ "$option" != "2" ]; do
    clear
    if [ "$language" == "1" ]
    then
      writeUserMessage "Instalação do optware no ASUS O!Play"
      writeUserMessage -e "\\n"    
      writeUserMessage "AVISO: ESTE SCRIPT IRÁ FORMATAR A DRIVE USB LIGADA AO SEU ASUS O!PLAY, APAGANDO TODOS OS SEUS CONTEÚDOS!!!"
      writeUserMessage -e "\\n"
      writeUserMessage "Por favor, introduza (1) para continuar, ou (2) para sair." 
    else
      writeUserMessage "ASUS O!Play optware installation"
      writeUserMessage -e "\\n"
      writeUserMessage "WARNING: THIS SCRIPT WILL FORMAT THE USB DRIVE CONNECTED TO YOUR ASUS O!PLAY, ERASING ALL ITS CONTENTS!!!"
      writeUserMessage -e "\\n"
      writeUserMessage "Please enter (1) to continue, or (2) to exit."
    fi
    read option
  done
  
  if [ "$option" == "1" ]
  then
    writeUserMessage -e "\\n"
    
    #verificar se o optware já foi instalado    
    executeOutputCommand cd /opt/bin
  
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "A verificar instalações prévias do optware..."
    else
      writeUserMessage "Checking for previous optware installations..."
    fi
      
    writeUserMessage -e "\\n"
    if [ `pwd` != "/opt/bin" ] 
    then
      if [ "$language" == "1" ]
      then
        writeUserMessage "=> Não foi detectada nenhuma versão instalada do optware."
        writeUserMessage "=> A prosseguir com a instação..."
      else
        writeUserMessage "=> Previous optware installation not detected."
        writeUserMessage "=> Proceeding with the installation..."
      fi
    else
      if [ "$language" == "1" ]
      then
        writeUserMessage "=> Anterior instalação do optware detectada! Instalação do optware abortada."
        writeUserMessage "=> Por favor reinstale o último firmware do ASUS O!Play, por forma a restaurar o sistema original. De seguida, execute novamente este script para instalar o sistema optware."
      else
        writeUserMessage "=> Previous optware installation detected! Optware installation procedure aborted."
        writeUserMessage "=> Please reinstall the latest ASUS O!Play firmware, in order to restore the original system. After that, execute this script again in order to install the optware system."
      fi
      executeOutputCommand exit 1
    fi
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "01. A efectuar o mount do disco interno do O!Play com permissões de escrita..."
    else
      writeUserMessage "01. Mounting O!Play's internal hdd with write permissions..."
    fi
    executeOutputCommand mount / -o remount,rw
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "02. A copiar a fonte 'arial.ttf' por cima da fonte asiátia 'WenQuanYiZH.ttf' para arranjar algum espaço no disco interno do O!Play..."
    else
      writeUserMessage "02. Copying 'arial.ttf' font over asian 'WenQuanYiZH.ttf' font to get some free space on the O!Play's internal hdd..."
    fi
    executeOutputCommand cp /usr/local/bin/Resource/arial.ttf /usr/local/bin/Resource/WenQuanYiZH.ttf                    
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "03. A criar um link simbólico para a directoria raíz do optware ('/opt' para '/tmp/usbmounts/sda1')..."
    else
      writeUserMessage "03. Creating a symbolic link to optware's root directory ('/opt' to '/tmp/usbmounts/sda1')..."
    fi
    executeOutputCommand ln -s /tmp/usbmounts/sda1 /opt
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "04. A efectuar o unmount do disco usb de sistema..."
    else
      writeUserMessage "04. Unmounting usb system disk.."
    fi
    executeOutputCommand umount /tmp/usbmounts/sda1   
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "05. A efectuar a formatação do disco usb com sistema de ficheiros linux (ext3)..."
    else
      writeUserMessage "05. Formatting usb drive with linux file system (ext3)..."
    fi
    executeOutputCommand mke2fs -j -M /opt -L opt /dev/discs/disc0/part1
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "06. A efectuar o mount do disco formatado na directoria do optware (/opt)..."
    else
      writeUserMessage "06. Mounting the formatted usb drive in optware directory (/opt)..."
    fi
    executeOutputCommand mount /dev/discs/disc0/part1 /tmp/usbmounts/sda1
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "07. A criar a directoria temporária para a instalação do optware (/opt/tmp)..."
    else
      writeUserMessage "07. Creating temporary directory for optware installation (/opt/tmp)..."
    fi
    executeOutputCommand mkdir /opt/tmp
    
    #mudar para a directoria temporária para o wget efectuar os downloads para lá
    executeOutputCommand cd /opt/tmp
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "08. A verificar a correcta formatação do disco usb no formato ext3..."
    else
      writeUserMessage "08. Checking for correct usb drive ext3 formatting..."
    fi
      
    writeUserMessage -e "\\n"
    if [ `pwd` != "/opt/tmp" ] 
    then
      if [ "$language" == "1" ]
      then
        writeUserMessage "=> Erro na formatação do disco usb. Por favor volte a executar este script por forma a repetir o processo de formatação."
      else
        writeUserMessage "=> Usb disk formatting error. Please re-execute this script to repeat the formatting process."
      fi
      exit 1 > /dev/null 2>&1
    else
      if [ "$language" == "1" ]
      then
        writeUserMessage "=> Formatação ext3 efectuada correctamente. A prosseguir com a instalação do optware..."
      else
        writeUserMessage "=> Ext3 formatting is OK. Proceeding with optware installation..."
      fi
      
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "09. A efectuar o download dos pacotes de instalação do optware..."
      else
        writeUserMessage "09. Downloading optware's install packages..."
      fi
      
      writeUserMessage -e "\\n"
      executeOutputCommand wget http://www.kovari.priv.hu/download/ipkg-cl.tgz
      writeUserMessage -e "\\n"    
      executeOutputCommand wget http://ipkg.nslu2-linux.org/feeds/optware/oleg/cross/stable/uclibc-opt_0.9.28-13_mipsel.ipk
      writeUserMessage -e "\\n"
      executeOutputCommand wget http://ipkg.nslu2-linux.org/feeds/optware/oleg/cross/stable/ipkg-opt_0.99.163-10_mipsel.ipk
      
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "10. A descompactar o instalador do optware..."
      else
        writeUserMessage "10. Extracting optware's installer..."
      fi
      executeOutputCommand tar -xvf ipkg-cl.tgz
      
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "11. A instalar o optware..."
      else
        writeUserMessage "11. Installing optware..."
      fi
      executeOutputCommand /opt/tmp/ipkg-cl install uclibc-opt_0.9.28-13_mipsel.ipk
      executeOutputCommand /opt/tmp/ipkg-cl install ipkg-opt_0.99.163-10_mipsel.ipk
      
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "12. A efectuar a limpeza dos ficheiros temporários de instalação do optware..."
      else
        writeUserMessage "12. Cleaning optware's installation temporary files..."
      fi
      executeOutputCommand rm /opt/tmp/*
      
      
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "13. A efectuar o update ao optware para a versão mais recente..."
      else
        writeUserMessage "13. Updating optware to the latest version..."
      fi
      executeOutputCommand /opt/bin/ipkg update
      
      
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "14. A instalar o editor 'nano'..."
      else
        writeUserMessage "14. Installing the 'nano' editor..."
      fi
      executeOutputCommand /opt/bin/ipkg install nano
      
      
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "15. A configurar o script de arranque das várias aplicações do optware (/usr/local/etc/rcS)..."
      else
        writeUserMessage "15. Configuring startup script for optware applications (/usr/local/etc/rcS)..."
      fi
      writeToFile "#------------------------------------" /usr/local/etc/rcS
      writeToFile "#lines added by A-OPTIS v0.1" /usr/local/etc/rcS
      writeToFile "#wait for the drive mount" /usr/local/etc/rcS
      writeToFile "sleep 150" /usr/local/etc/rcS
      writeToFile "#execute the service startup script" /usr/local/etc/rcS
      writeToFile "/tmp/usbmounts/sda1/startup" /usr/local/etc/rcS
      writeToFile "#------------------------------------" /usr/local/etc/rcS
      
      
      
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "16. A escrever o script de arranque das várias aplicações do optware (/opt/startup)..."
      else
        writeUserMessage "16. Writing startup script for optware applications (/opt/startup)..."
      fi
      writeToFile "#---------------------------------------------------------" /opt/startup
      writeToFile "# lines added by A-OPTIS v0.1" /opt/startup 
      writeToFile "#!/bin/sh" /opt/startup
      writeToFile "#start the optware services" /opt/startup
      writeToFile "for i in /opt/etc/init.d/S??* ;do" /opt/startup
      writeToFile "\$i start&" /opt/startup
      writeToFile "done" /opt/startup
      writeToFile "exit 0" /opt/startup
      writeToFile "#---------------------------------------------------------" /opt/startup
      executeOutputCommand chmod +x /opt/startup
  
  
      writeUserMessage -e "\\n"
      if [ "$language" == "1" ]
      then
        writeUserMessage "17. A adicionar as aplicações optware ao PATH, para facilitar o uso em linha de comandos (/opt/bin)..."
      else
        writeUserMessage "17. Adding optware applications to PATH, to facilitate command-line usage (/opt/bin)..."
      fi
      writeToFile "PATH=$PATH:/opt/bin" /etc/profile 
      
      
      restartOption = 0
      while [ "$restartOption" != "1"  ] && [ "$restartOption" != "2" ]; do
        clear
        if [ "$language" == "1" ]
        then
          writeUserMessage ".........................................................................."
          writeUserMessage "=> Instalação do optware no ASUS O!Play concluída!"
          writeUserMessage "=> Pode agora efectuar a instalação das diversas aplicações disponíveis."
          writeUserMessage "=> Lista de aplicações optware: http://www.nslu2-linux.org/wiki/Optware/Packages"
          writeUserMessage ".........................................................................."
          writeUserMessage -e "\\n"
          writeUserMessage "--------------------------------------------------------------------------"
          writeUserMessage "=> O sistema precisa de ser reiniciado! Introduza (1) para reiniciar o O!play agora, ou (2) para reiniciar manualmente mais tarde."
          writeUserMessage "--------------------------------------------------------------------------"
        else
          writeUserMessage ".........................................................................."
          writeUserMessage "=> ASUS O!Play optware installation completed!"
          writeUserMessage "=> You can now install the available optware applications."
          writeUserMessage "=> Optware applications list: http://www.nslu2-linux.org/wiki/Optware/Packages"
          writeUserMessage ".........................................................................."
          writeUserMessage -e "\\n"
          writeUserMessage "--------------------------------------------------------------------------"                           
          writeUserMessage "=> The system needs to be restarted! Enter (1) to restart O!Play now, or (2) to restart manually later."
          writeUserMessage "--------------------------------------------------------------------------"
        fi
        read restartOption
      done
      
      if [ "$restartOption" == "1" ]
      then
        if [ "$language" == "1" ]
        then
          writeUserMessage "A reiniciar o ASUS O!Play. Aguarde um momento..."
        else
          writeUserMessage "Restarting ASUS O!Play. Wait a moment..."
        fi
        executeOutputCommand reboot
      else
        executeOutputCommand exit 0
      fi
    fi                                     
  fi

#2 - instalação de aplicações optware
elif [ "$installOption" == "2" ]
then

  appOption = 0
  while [ "$appOption" != "1"  ] && [ "$appOption" != "2" ] && [ "$appOption" != "3" ] && [ "$appOption" != "4" ]; do
    clear
    if [ "$language" == "1" ]
    then
      writeUserMessage "Instalação de aplicações optware no ASUS O!Play"
      writeUserMessage -e "\\n"
      writeUserMessage "=> (1) Servidor de SSH e SFTP (OpenSSH)"
      writeUserMessage "=> (2) Cliente de BitTorrent (Transmission)"
      writeUserMessage "=> (3) Servidor NAS - SMB/CIFS (Samba)"
      writeUserMessage "=> (4) Sair"
    else
      writeUserMessage "ASUS O!Play optware application installation"
      writeUserMessage -e "\\n"
      writeUserMessage "=> (1) SSH and SFTP Server (OpenSSH)"
      writeUserMessage "=> (2) BitTorrent Client (Transmission)"
      writeUserMessage "=> (3) NAS - SMB/CIFS Server (Samba)"
      writeUserMessage "=> (4) Exit"
    fi
    read appOption
  done      
      
  if [ "$appOption" != "4" ]
  then
    #verificar se o optware está correctamente instalado    
    executeOutputCommand cd /opt/bin
  
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "A verificar a instalação do sistema optware..."
    else
      writeUserMessage "Verifying optware system installation..."
    fi
      
    writeUserMessage -e "\\n"
    if [ `pwd` != "/opt/bin" ] 
    then
      if [ "$language" == "1" ]
      then
        writeUserMessage "=> Erro! O sistema optware não se encontra correctamente instalado."
        writeUserMessage "=> Por favor reinstale o último firmware do ASUS O!Play, por forma a restaurar o sistema original. De seguida, execute novamente este script para instalar o sistema optware."
      else
        writeUserMessage "=> Error! Optware system is not correctly installed."
        writeUserMessage "=> Please reinstall the latest ASUS O!Play firmware, in order to restore the original system. After that, execute this script again in order to install the optware system."
      fi
      executeOutputCommand exit 1
    else
      if [ "$language" == "1" ]
      then
        writeUserMessage "=> Optware detectado!"
      else
        writeUserMessage "=> Optware detected!"
      fi
    fi
  fi
  
  #1 - OpenSSH
  if [ "$appOption" == "1" ]
  then
    clear
    if [ "$language" == "1" ]
    then
      writeUserMessage "Instalação do OpenSSH"
      writeUserMessage -e "\\n"
      writeUserMessage "01. A efectuar o mount do disco interno do O!Play com permissões de escrita..."
    else
      writeUserMessage "OpenSSH Installation"
      writeUserMessage -e "\\n"
      writeUserMessage "01. Mounting O!Play's internal hdd with write permissions..."
    fi    
    executeOutputCommand mount / -o remount,rw
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "02. A instalar o OpenSSH. Por favor aguarde..."
    else
      writeUserMessage "02. Installing OpenSSH. Please wait..."
    fi
    
    writeUserMessage -e "\\n"
    executeOutputCommand /opt/bin/ipkg update
    writeUserMessage -e "\\n"
    executeOutputCommand /opt/bin/ipkg install openssh
    writeUserMessage -e "\\n"    
    executeOutputCommand /opt/bin/ipkg install openssh-sftp-server
    
    clear    
    if [ "$language" == "1" ]
    then
      writeUserMessage ".........................................................................."
      writeUserMessage "Instalação do OpenSSH concluída."
      writeUserMessage -e "\\n"
      writeUserMessage "É necessário criar manualmente uma password para a conta do utilizador 'root' no O!Play antes de poder utilizar o OpenSSH."
      writeUserMessage "Para tal, digite agora 'passwd' na linha de comandos."
      writeUserMessage ".........................................................................."
      writeUserMessage -e "\\n"
      writeUserMessage "--------------------------------------------------------------------------"
      writeUserMessage "AVISO: O seu ASUS está neste momento temporariamente com acesso de escrita ao sistema apenas para que possa definir a sua password!!!"
      writeUserMessage "Assim que efectuar o reboot, o disco interno do ASUS estará novamente protegido contra escrita acidental." 
      writeUserMessage -e "\\n"
      writeUserMessage "Depois disso, reinicie o O!Play digitando 'reboot' na linha de comandos, ou desligando e ligando o O!Play da corrente."
      writeUserMessage "--------------------------------------------------------------------------"
    else
      writeUserMessage ".........................................................................."
      writeUserMessage "OpenSSH installation completed."
      writeUserMessage -e "\\n"
      writeUserMessage "It's necessary to create a password for the O!Play 'root' user before using OpenSSH."
      writeUserMessage "In order to do this, type 'passwd' now at the command prompt."
      writeUserMessage ".........................................................................."
      writeUserMessage -e "\\n"
      writeUserMessage "--------------------------------------------------------------------------"
      writeUserMessage "WARNING: Your ASUS now has temporary system write access in order to enable you to set your password!!!"
      writeUserMessage "As soon as you reboot, the ASUS internal disk will once again be write-protected against accidental writing."
      writeUserMessage -e "\\n"
      writeUserMessage "Afterwards, restart O!Play by typing 'reboot' at the command prompt, or by shutting down O!Play from the power, and then starting it up."
      writeUserMessage "--------------------------------------------------------------------------"
    fi
    
    
  
  #2 - Transmission
  elif [ "$appOption" == "2" ]
  then
    clear
    if [ "$language" == "1" ]
    then
      writeUserMessage "Instalação do Transmission"
      writeUserMessage -e "\\n"
      writeUserMessage "01. A efectuar o mount do disco interno do O!Play com permissões de escrita..."
    else
      writeUserMessage "Transmission Installation"
      writeUserMessage -e "\\n"
      writeUserMessage "01. Mounting O!Play's internal hdd with write permissions..."
    fi    
    executeOutputCommand mount / -o remount,rw
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "02. A instalar o Transmission. Por favor aguarde..."
    else
      writeUserMessage "02. Installing Transmission. Please wait..."
    fi
    writeUserMessage -e "\\n"
    executeOutputCommand /opt/bin/ipkg update
    writeUserMessage -e "\\n"
    executeOutputCommand /opt/bin/ipkg install transmission
    
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "03. A criar directorias necessárias ao Transmission ('/opt/Downloads' e '/opt/Configs')..."
    else
      writeUserMessage "03. Creating needed Transmission directories ('/opt/Downloads' and '/opt/Configs')..."
    fi
    executeOutputCommand mkdir /opt/Configs
    executeOutputCommand mkdir /opt/Downloads
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "04. A configurar o Transmission..."
    else
      writeUserMessage "04. Configuring Transmission..."
    fi
    executeOutputCommand /opt/bin/transmission-daemon -g /opt/Configs -w /opt/Downloads -a "127.0.0.1,192.168.*.*"
    executeOutputCommand sleep 15
    executeOutputCommand killall transmission-daemon
    executeOutputCommand mkdir /opt/etc
    executeOutputCommand mkdir /opt/etc/init.d
    
    writeToFile "#!/bin/sh" /opt/etc/init.d/S88transmission
    writeToFile "export PATH=/opt/bin:$PATH" /opt/etc/init.d/S88transmission
    writeToFile "if [ -n \"`pidof transmission-daemon`\" ]; then" /opt/etc/init.d/S88transmission
    writeToFile "  killall transmission-daemon" /opt/etc/init.d/S88transmission 
    writeToFile "fi" /opt/etc/init.d/S88transmission
    writeToFile "transmission-daemon -g /opt/Configs" /opt/etc/init.d/S88transmission
    
    executeOutputCommand chmod +x /opt/etc/init.d/S88transmission
    
    writeToFile "#!/bin/sh" /opt/etc/init.d/K88transmission 
    writeToFile "killall transmission-daemon" /opt/etc/init.d/K88transmission
    
    executeOutputCommand chmod +x /opt/etc/init.d/K88transmission
    

    clear
    if [ "$language" == "1" ]
    then
      writeUserMessage ".........................................................................."
      writeUserMessage "Instalação do Transmission concluída."
      writeUserMessage -e "\\n"
      writeUserMessage "Pode aceder ao Transmission através do seu browser => http://colocar-aqui-ip-do-asus:9091/"
      writeUserMessage -e "\\n"
      writeUserMessage "NOTA 1: É necessário abrir manualmente o porto 51413 no router ligado ao O!Play (port forwarding de 51413 para 51413)."
      writeUserMessage -e "\\n"
      writeUserMessage "NOTA 2: O Transmission está configurado para acesso por rede local só."
      writeUserMessage "        Para acesso remoto fora da rede local, edite o campo "rpc-whitelist" no ficheiro de configuração '/opt/Configs/settings.json'."
      writeUserMessage -e "\\n"
      writeUserMessage "NOTA 3: A directoria de downloads por omissão está configurada para '/opt/Downloads' no disco de sistema."
      writeUserMessage "        Recomenda-se que altere esta directoria com o interface web do Transmission para outro disco."
      writeUserMessage ".........................................................................."
      writeUserMessage -e "\\n"          
      writeUserMessage "--------------------------------------------------------------------------"                                                                                                                     
      writeUserMessage "É necessário reiniciar o O!Play. Para tal, digite 'reboot' na linha de comandos, ou desligue e ligue o O!Play da corrente."
      writeUserMessage "--------------------------------------------------------------------------" 
    else
      writeUserMessage ".........................................................................."
      writeUserMessage "Transmission intallation completed."
      writeUserMessage -e "\\n"
      writeUserMessage "You can access Transmission via browser => http://put-asus-ip-here:9091"
      writeUserMessage -e "\\n"
      writeUserMessage "NOTE 1: It's necessary to manually open port 51413 on the router connected to O!Play (port forwarding from 51413 to 51413)."
      writeUserMessage -e "\\n"
      writeUserMessage "NOTE 2: Transmission is configured from local network access only."
      writeUserMessage "        In order to use remote acess outside the local network, edit the "rpc-whitelist" field on the '/opt/Configs/settings.json' config file."
      writeUserMessage -e "\\n"
      writeUserMessage "NOTE 3: The default downloads directory is '/opt/Downloads' in the system disk."
      writeUserMessage "        It's recommended that this directory be altered to another disk with Transmission's web interface."
      writeUserMessage ".........................................................................."
      writeUserMessage -e "\\n" 
      writeUserMessage "--------------------------------------------------------------------------"
      writeUserMessage "O!Play must be restarted. To do so, type 'reboot' at the command prompt, or turn it off from the power supply and then back on again."
      writeUserMessage "--------------------------------------------------------------------------"
    fi
    
    
    
    
    
    
  #3 - Samba
  elif [ "$appOption" == "3" ]
  then
    clear
    if [ "$language" == "1" ]
    then
      writeUserMessage "Instalação do Samba"
      writeUserMessage -e "\\n"
      writeUserMessage "01. A efectuar o mount do disco interno do O!Play com permissões de escrita..."
    else
      writeUserMessage "Samba Installation"
      writeUserMessage -e "\\n"
      writeUserMessage "01. Mounting O!Play's internal hdd with write permissions..."
    fi    
    executeOutputCommand mount / -o remount,rw 
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "02. A instalar o Samba. Por favor aguarde..."
    else
      writeUserMessage "02. Installing Samba. Please wait..."
    fi
    writeUserMessage -e "\\n"
    executeOutputCommand /opt/bin/ipkg update
    writeUserMessage -e "\\n"
    executeOutputCommand /opt/bin/ipkg install samba2
    
    
    writeUserMessage -e "\\n"
    if [ "$language" == "1" ]
    then
      writeUserMessage "03. A configurar o Samba..."
    else
      writeUserMessage "03. Configuring Samba..."
    fi
    executeOutputCommand rm /opt/etc/samba/smb.conf
    
    writeToFile "#=============================================================================" /opt/etc/samba/smb.conf
    writeToFile "#A-OPTIS Samba Configuration File" /opt/etc/samba/smb.conf
    writeToFile "#======================= Global Settings =====================================" /opt/etc/samba/smb.conf
    writeToFile "[global]" /opt/etc/samba/smb.conf
    writeToFile "#Netbios Name" /opt/etc/samba/smb.conf
    writeToFile "netbios name = ASUS O!Play" /opt/etc/samba/smb.conf
    writeToFile "# workgroup = NT-Domain-Name or Workgroup-Name" /opt/etc/samba/smb.conf
    writeToFile "workgroup = WORKGROUP" /opt/etc/samba/smb.conf
    writeToFile "# server string is the equivalent of the NT Description field" /opt/etc/samba/smb.conf
    writeToFile "server string = Samba Optware Server" /opt/etc/samba/smb.conf
    writeToFile "#security" /opt/etc/samba/smb.conf
    writeToFile "hosts allow = 192.168. 127." /opt/etc/samba/smb.conf
    writeToFile "valid users = root" /opt/etc/samba/smb.conf
    writeToFile "security = user" /opt/etc/samba/smb.conf
    writeToFile "encrypt passwords = yes" /opt/etc/samba/smb.conf
    writeToFile "#log file" /opt/etc/samba/smb.conf
    writeToFile "log file = /opt/var/log/samba/log.%m" /opt/etc/samba/smb.conf
    writeToFile "max log size = 50" /opt/etc/samba/smb.conf
    writeToFile "#performance tweak" /opt/etc/samba/smb.conf
    writeToFile "socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192" /opt/etc/samba/smb.conf
    writeToFile "#DNS Proxy" /opt/etc/samba/smb.conf
    writeToFile "dns proxy = no" /opt/etc/samba/smb.conf
    writeToFile "#============================ Share Definitions ==============================" /opt/etc/samba/smb.conf
    writeToFile "[Usb]" /opt/etc/samba/smb.conf
    writeToFile "comment = USB disks" /opt/etc/samba/smb.conf
    writeToFile "browseable = yes" /opt/etc/samba/smb.conf
    writeToFile "writable = yes" /opt/etc/samba/smb.conf
    writeToFile "path = /tmp/usbmounts/" /opt/etc/samba/smb.conf
    writeToFile "[Asus]" /opt/etc/samba/smb.conf
    writeToFile "comment = ASUS O!Play file system" /opt/etc/samba/smb.conf
    writeToFile "browseable = yes" /opt/etc/samba/smb.conf
    writeToFile "writable = no" /opt/etc/samba/smb.conf
    writeToFile "path = /" /opt/etc/samba/smb.conf
    

    clear
    if [ "$language" == "1" ]
    then
      writeUserMessage ".........................................................................."
      writeUserMessage "Instalação do Samba concluída."
      writeUserMessage -e "\\n"
      writeUserMessage "É necessário criar manualmente uma password para a conta do utilizador 'root' no O!Play antes de poder utilizar o Samba."
      writeUserMessage "Para tal, digite agora 'smbpasswd -a root' na linha de comandos."
      writeUserMessage ".........................................................................."
      writeUserMessage -e "\\n"
      writeUserMessage "--------------------------------------------------------------------------"
      writeUserMessage "AVISO: O seu ASUS está neste momento temporariamente com acesso de escrita ao sistema apenas para que possa definir a sua password!!!"
      writeUserMessage "Assim que efectuar o reboot, o disco interno do ASUS estará novamente protegido contra escrita acidental." 
      writeUserMessage -e "\\n"
      writeUserMessage "É necessário reiniciar o O!Play. Para tal, digite 'reboot' na linha de comandos, ou desligue e ligue o O!Play da corrente."
      writeUserMessage "--------------------------------------------------------------------------" 
    else    
      writeUserMessage ".........................................................................."
      writeUserMessage "Samba intallation concluded."
      writeUserMessage -e "\\n"
      writeUserMessage "It's necessary to create a password for the O!Play 'root' user before using Samba."
      writeUserMessage "In order to do this, type 'smbpasswd -a root' now at the command prompt."
      writeUserMessage ".........................................................................."
      writeUserMessage -e "\\n"
      writeUserMessage "--------------------------------------------------------------------------"
      writeUserMessage "WARNING: Your ASUS now has temporary system write access in order to enable you to set your password!!!"
      writeUserMessage "As soon as you reboot, the ASUS internal disk will once again be write-protected against accidental writing."
      writeUserMessage -e "\\n"
      writeUserMessage "O!Play must be restarted. To do so, type 'reboot' at the command prompt, or turn it off from the power supply and then back on again."
      writeUserMessage "--------------------------------------------------------------------------"
    fi
  
  else
    exit 0
  fi
  
else
  exit 0
fi
