#!/ffp/bin/sh
export PATH=/opt/bin:/opt/sbin:/sbin:/bin:/usr/sbin:/usr/bin
COMMAND="python pyLoadCore.py --configdir=/opt/pyload/.pyload"
TOPDIR=/opt
INSTALLDIR=$TOPDIR/pyload
BACKUPDIR=$TOPDIR/pyload-backup

func_download_pyload() {
    echo "Downloading newest version of pyLoad"
    # Clear directory
    rm -Rf $BACKUPDIR/pyload-download
    # Create directory
    mkdir -p $BACKUPDIR/pyload-download
    [[ $? -gt 0 ]] && echo "Download dir could not be created" && return 1
    # Change to directory
    cd $BACKUPDIR/pyload-download
    # Download via wget
    echo "Downloading new version"
    wget http://get.pyload.org/get/src/
    [[ $? -gt 0 ]] && echo "Download not possible" && return 1
    # Unzip
    echo "Unzipping new version"
    unzip pyload-src*.zip
    [[ $? -gt 0 ]] && echo "Unzip not sucessful" && return 1
    rm pyload-src-*.zip
    # Instead of downloading a stable you could also download from hg, e.g. spoobs branch:
    #/opt/bin/hg-py2.7 clone -b stable https://bitbucket.org/spoob/pyload
    #[[ $? -gt 0 ]] && echo "Clone not successful" && return 1
}

func_install_pyload_files() {
    if [[ -d $BACKUPDIR/pyload-download ]]; then
        echo "Installation of Pyload started"
        cp -R $BACKUPDIR/pyload-download/pyload $TOPDIR
        [[ $? -gt 0 ]] && echo "Install not sucessful" && return 1
		echo "Installation of Pyload ended"
    else
        echo "Pyload not downloaded yet, execute func_download_pyload before"
    fi
}

func_backup_config_dir() {
    if [[ -d $INSTALLDIR/.pyload ]]; then
        echo "Backing up configuration data"
        mkdir -p $BACKUPDIR/pyload-config
        cp -R $INSTALLDIR/.pyload $BACKUPDIR/pyload-config/
        [[ $? -gt 0 ]] && echo "Backup not sucessful" && return 1
    fi
}

func_restore_config_dir() {
    if [[ -d $BACKUPDIR/pyload-config/.pyload ]]; then
        if [[ -d $INSTALLDIR ]]; then
            echo "Restoring configuration data"
			rm -Rf $INSTALLDIR/.pyload
            cp -R $BACKUPDIR/pyload-config/.pyload $INSTALLDIR/
        fi
    fi
}

func_restore_old_config() {
    func_restore_config_dir
    [[ $? -gt 0 ]] && echo "Restore of configuration dir not sucessful" && return 1
    # Change configuration path
    echo "Press enter when asked for a path"
    python pyLoadCore.py --changedir --configdir=/opt/pyload/.pyload
}

func_generate_new_config() {
    func_restore_config_dir
    echo "In case of question, check:"
    echo " - http://wolf-u.li/3921/     (German  Tutorial)"
    echo " - http://nas-tweaks.net/220/ (English Tutorial)"
    echo "Press enter when asked for a path:"
    python pyLoadCore.py --changedir --configdir=/opt/pyload/.pyload
    echo "Running Setup in the next step:"
    # Run Setup
    python pyLoadCore.py -s
}
    
func_start() {
    echo "Starting PyLoad"
    cd $INSTALLDIR
    $COMMAND --daemon
}

func_status() {
    echo -n "Status of PyLoad: "
    cd $INSTALLDIR
    STATUS=$($COMMAND --status)
    if [[ $STATUS = "False" ]]; then
        echo "Not running"
    else
        echo "Running as PID $STATUS"
    fi
}

func_stop() {
    echo "Stopping PyLoad"
    cd $INSTALLDIR
    $COMMAND --quit
}

func_update_prepare() {
    # Try download:
    func_download_pyload
	[[ $? -gt 0 ]] && echo "Download failed" && return 1
    # Download successful, backup data:
    if [[ -d $BACKUPDIR/pyload-old ]]; then
        if [[ ! -d $INSTALLDIR ]]; then
            echo "$INSTALLDIR does not exist, looks like an error!"
            exit 1;
        else
            echo "Deleting old backup directory in $BACKUPDIR"
            rm -rf $INSTALLDIR/pyload-old
            [[ $? -gt 0 ]] && echo "Backup deletion failed" && return 1
		fi
        echo "Done"
    fi
}

func_update_execute(){
    #update_prepare needs to be executed first!
    cd $INSTALLDIR
    echo "Backup of your pyLoad Directory in $TOPDIR"
    mv $INSTALLDIR $BACKUPDIR/pyload-old
    echo "Seperate backup of your configuration data"
    func_backup_config_dir
    func_install_pyload_files
    cd $INSTALLDIR
	echo ""
	echo "Keep old config or create a new one?"
    PS3='Keep old config or create a new one?: '
    select OLDNEWCONFIG in 'Old' 'New'
    do
        if [[ -n $OLDNEWCONFIG ]]; then
			echo "You have chosen: $OLDNEWCONFIG"
			if [[ $OLDNEWCONFIG = "Old" ]]; then
				echo "Keeping old configuration"
				func_restore_old_config
				[[ $? -gt 0 ]] && echo "configuration restore failed" && return 1
			elif [[ $OLDNEWCONFIG = "New" ]]; then
				echo "Generating new configuration"
				func_generate_new_config
			fi
			break
        else
            func_echo "Invalid choice ($OLDNEWCONFIG). Please try again";
        fi
    done
}

func_install() {
	func_download_pyload
	[[ $? -gt 0 ]] && echo "Download failed" && exit 1
	func_install_pyload_files
	[[ $? -gt 0 ]] && echo "Install failed" && exit 1
	func_generate_new_config
	func_backup_config_dir
}

case "$1" in
    start)
        func_start
        ;;
    stop)
        func_stop
        ;;
    restart)
        func_stop
        sleep 4
        func_start
        ;;
    status)
        func_status
        ;;
    install)
        func_install
		func_start
		;;
    update)
        func_update_prepare
		[[ $? -gt 0 ]] && echo "Update preparation failed" && exit 1
        func_stop
        sleep 4
        func_update_execute
		[[ $? -gt 0 ]] && echo "Update execution failed" && exit 1
        func_start
        ;;
    *)
        echo "Usage: $0 (start|stop|restart|status|update)"
        exit 1
        ;;
esac
exit 0