Showing posts with label Ubuntu. Show all posts
Showing posts with label Ubuntu. Show all posts

14 March 2011

How to enable color prompt in byobu

Byobu sets $TERM environment variable to screen-bce, screen.linux, or something beginning with screen(at least currently in Ubuntu 10.10). And if you have your bash prompt normally colorized, it probably won't work in byobu without some changes in ~/.bashrc.

To enable color prompt in boybu find out what's the value of $TERM within byobu:
$ echo $TERM
screen-bce
Now in ~/.bashrc find lines like
# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm*) color_prompt=yes;;
and append the following line there:
    screen*) color_prompt=yes;;
Then find lines like:
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
and change them to:
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*|screen*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"

Here is my ~/.bashrc:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# don't put duplicate lines in the history. See bash(1) for more options
# don't overwrite GNU Midnight Commander's setting of `ignorespace'.
#export HISTCONTROL=$HISTCONTROL${HISTCONTROL+,}ignoredups
# ... or force ignoredups and ignorespace
export HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
export HISTSIZE=1000
export HISTFILESIZE=3000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm*) color_prompt=yes;;
    screen*) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
 # We have color support; assume it's compliant with Ecma-48
 # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
 # a case would tend to support setf rather than setaf.)
 color_prompt=yes
    else
 color_prompt=
    fi
fi
if [[ "$color_prompt" = yes && "$USER" = root ]]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]: \[\033[01;34m\]\w\[\033[00m\] \$ '
elif [[ "$color_prompt" = yes ]]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[00;33m\]\u@\h\[\033[00m\]: \[\033[01;34m\]\w\[\033[00m\] \$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w \$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*|screen*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# Alias definitions.
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
fi

export EDITOR='vim'
export GREP_COLOR=';33'
#export PATH=$PATH:/usr/local/mysql/bin:/usr/local/mysql/sbin

11 March 2011

Change wallpaper periodically in Ubuntu

Thanks to UbuntuForums.org, I made a simple cron job changing desktop wallpaper depending on time.

crontab

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
@hourly /share/scripts/bash/change_wallpaper.sh

change_wallpaper.sh

#!/bin/bash -
# Get the pid of nautilus
nautilus_pid=$(pgrep -u $LOGNAME -n nautilus)
# If nautilus isn't running, just exit silently
if [ -z "$nautilus_pid" ]; then
    exit 0
fi
# Grab the DBUS_SESSION_BUS_ADDRESS variable from nautilus's environment
eval $(tr '\0' '\n' < /proc/$nautilus_pid/environ | grep '^DBUS_SESSION_BUS_ADDRESS=')
# Check that we actually found it
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
    echo "Failed to find bus address" >&2
    exit 1
fi
# export it so that child processes will inherit it
export DBUS_SESSION_BUS_ADDRESS
HOUR=$(date +%H)
PICDIR="/usr/share/backgrounds/"
#echo "HOUR: $HOUR"
#echo "PICDIR: $PICDIR"
case $HOUR in
21|22|23|00|01|02|03|04|05|06)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"NATURE-ZenLizard.png"
;;
12|13|14|15|16|17|18|19|20)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Fern_by_aalex04.jpg" 
;;
09|10|11)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Bon-Echo_wallpaper.jpg"
;;
*)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Ropey_Photo_by_Bob_Farrell.jpg"
;;
esac

I wonder, why it didn't work without DBUS_SESSION_BUS_ADDRESS detection. However, it works now. I'd be glad, if it helps someone.

11 November 2010

Enable/Disable Apache virtual hosts on Ubuntu with Zenity

Here is a simple bash script I use to toggle virtual hosts in a GUI window.

#!/bin/bash
# get available & enables site names & set corresp-ly checkboxes in the following zenity list
vh_avail=(`ls -B /etc/apache2/sites-available/`);

i=0
s=""

while (( i< ${#vh_avail[*]} ))
do
 if [ -f /etc/apache2/sites-enabled/${vh_avail[$i]} ] ; then 
  s=$s"TRUE "
 else 
  s=$s"FALSE "
 fi
 s=$s${vh_avail[$i]}" "
 
 (( ++i ))
done

# get vhost name

vhosts=`(zenity --list --width=700 --height=500 --title="Choose vhost" \
 --checklist --column="" --column="vhost" $s)`;

case $? in 
 0) # OK
   a=(`echo "$vhosts"|tr "\|" " "`);
   i=0;
   di=0;
   
   #disable all
   
   while (( i< ${#vh_avail[*]} ))
   do
    if [ -f /etc/apache2/sites-enabled/${vh_avail[$i]} ] ; then 
     a2dissite ${vh_avail[$i]}
    fi
    (( ++i ))
   done
   
   # enable needed
   i=0;   
   while ((i < ${#a[*]}))
   do 
    if [ -f /etc/apache2/sites-available/${a[$i]} ] ; then
     a2ensite ${a[i++]}
    else
     (( di++ ))
    fi
   done 
   
   info="${#a[*]} vhosts enabled";
   
   if (( di>0 ));then
    info="$info\n$di vhosts not found in /etc/apache2/sites-available/"
    zenity --warning --text="$info"
   else 
    zenity --info --text="$info"
   fi
   
   # reload apache
   /etc/init.d/apache2 restart #reload not always works
  ;;
 1) # Cancel
  exit 0
  ;; 
esac
So you can make a desktop launcher with command
gksudo /share/scripts/bash/vhosts_ed.sh

06 November 2010

How to convert MP3 file tag encodings in Ubuntu

It was somewhat troublesome for me to convert ID3 tags for large amount of files, especially in case of file names, with spaces and other "special" characters. I found tools and managed to successfully convert Windows-1251 MP3 file tags to UTF-8. I also post a sample bash script here.

mp3info

This tool displays and modifies ID3 tags. Quite simple in use. I would deal with it, if there were no problems with long character sequences(just cuts unpredictably!).

mid3iconv

It's job is exactly what I want. Converts ID3 tag encodings to Unicode. Usage is simplisity itself, e.g.
$ mid3iconv -e "Windows-1251" ~/Music/sample.mp3

Sample bash script

So the task is to iterate each file and apply mid3iconv. But one should care files already having Unicode tags. Therefore, the following script tries to detect encoding by means of enca tool.

#!/bin/bash 
# Splits the first argument by delimeter specified by the 2nd parameter 
# E.g. my_split_str $string $delim
# If delimeter is not specified, the func defaults to '='
# Requirements: 
# enca
# mp3info
# python-mutagen (mid3iconv)
#
# Example: bash mp3id3enc.sh --from-code=Windows-1251 --to-code=UTF-8
function my_split_str()
{
    if (( $# <=1 )) 
    then 
        IFS='=' 
    else 
        IFS=$2 
    fi 
    set -- $1
    echo $*
}

function usage()
{
    echo $0" [options]"
    echo "Options:
    --src-dir       Source dir
    --auto-detect-enc       Whether try to auto detect source encoding. Default: 0
    --from-code     Source text encoding. Default: Windows-1251
    --to-code       Target text encoding. Default: UTF-8
    --guess-lang        Language to use when guessing source text encoding. Default: ru
    "
    exit 1
}

# Set option defaults
src_dir='./'                # source directory
auto_detect_enc=0           # auto detect source encoding
from_code='Windows-1251'
to_code='UTF-8'
guess_lang='ru'

# Get options
for i in $*
do
  o=(`my_split_str $i '='`)
  case ${o[0]} in
    --src-dir)
        src_dir=${o[1]}
        # Add trailing slash, if not added yet
        if [[ ${src_dir#${src_dir%?}} != '/' ]]; then src_dir=$src_dir"/"; fi
      ;;
    --from-code)
      from_code=${o[1]}
      ;;
    --to-code)
      to_code=${o[1]}
      ;;
    --guess-lang)
      guess_lang=${o[1]}
      ;;
    --auto-detect-enc)
      auto_detect_enc=1
      ;;
    --help)
        usage
        exit 1
      ;;
    *)
      # unknown option
      echo "Unknown option ${o[0]}"
      usage
      exit 2
      ;;
  esac
done

find "$src_dir" -name "*.mp3" | while read FILENAME
do
    echo "$FILENAME..."

    # Try to detect encoding
    if [[ $auto_detect_enc = 1 ]]; then
        e=`mp3info -p "%t" "$FILENAME" | enca -gL $guess_lang`

        if [[ "$e" = *1251* ]]; then 
            from_code="Windows-1251"
        elif [[ "$e" = *CP866* || "$e" = *866* ]]; then
            from_code="CP866"
        elif [[ "$e" = *KOI8-R* ]]; then
            from_code="KOI8-R"
        else
            echo "couldn't detect encoding for "$FILENAME
            echo "$FILENAME ($e)" >> not-detected.log 
            continue
        fi

        echo "detected encoding: "$from_code
    fi

    t=`mp3info -p "%t" "$FILENAME" | enca -L ru`

    # For unrecognized encoding assume Windows-1251 
    if [[ $t = *Unrecognized* ]]; then 
        t="Windows-1251"
    fi
    echo "t='$t'"
    if [[ $t != *866* && $t != *1251* ]]; then 
        echo "$FILENAME skipped"
        continue
    fi

    mid3iconv -e "$from_code" "$FILENAME"

    echo
done
Notice, loop like

for FILENAME in $(find $src_dir -name "*.mp3"); do
...
done
fails with file names containing spaces and other escape sequences.

16 August 2010

Compiling Debian package for MySQL 5.1 with SphinxSE

I'd share experiense of compiling MySQL with SphinxSE Debian-way, i.e. making a DEB package from MySQL and SphinxSE sources. I pick an easy way using checkinstall. Checkinstall implies quick-and-dirty solution. If you want package complied Debian policy, you are not on the right spot(go here; this gives an overview). Ubuntu standard packages don't always provide latest releases. At least it regards to both sphinxsearch and mysql-server. If you already have MySQL installed, remove it:
$ sudo apt-get remove --purge mysql-server-5.1
UPDATE 19.08.2010 Otherwise, you should create a group and a user for MySQL as described here After that which mysql command should return an empty reply. Download Sphinx source tarball and untar it. We'll need just it's mysqlse folder. For instance, I'm checking out 1.10 beta release now. So I refer to sphinx-1.10-beta folder below. Download MySQL source for generic Linux platform and untar it:
$ tar -xf mysql-5.1.49.tar.gz
Currently 5.1.49 is the latest version. So I refer to mysql-5.1.49 folder below. Copy Sphinx mysqlse folder to mysql-5.1.49/storage/sphinx/:
$ cp -R sphinx-1.10-beta/mysqlse/ mysql-5.1.49/storage/sphinx/
Configure and precompile MySQL:
$ cd mysql-5.1.49
$ sh BUILD/autorun.sh
$ ./configure \
--prefix=/usr/local/mysql \
--with-plugins=sphinx \
--enable-assembler \
--with-mysqld-ldflags=-all-static \
--with-server-suffix=' SphinxSE 1.10 beta' \
--with-charset=utf8 
$ make && sudo make install 
Instead of sudo make install:
$ sudo checkinstall -D \
--pkgname=mysql-server-5.1.49_sphinxse-1.10b \
--pkgversion=1.0
You should receive output like
...
======================== Installation successful ==========================

Copying documentation directory...
./
./README
./ChangeLog
./Docs/
./Docs/Makefile
./Docs/Makefile.am
./Docs/INSTALL-BINARY
./Docs/mysql.info
./Docs/Makefile.in
./INSTALL-SOURCE
./COPYING
./INSTALL-WIN-SOURCE
grep: /var/tmp/tmp.FFdtipwofv/newfile: No such file or directory

Copying files to the temporary directory...OK

Stripping ELF binaries and libraries...OK

Compressing man pages...OK

Building file list...OK

Building Debian package...OK

Installing Debian package...OK

Erasing temporary files...OK

Writing backup package...OK

Deleting temp dir...OK


**********************************************************************

 Done. The new package has been installed and saved to

 /home/ruslan/now/mysql-5.1.49/mysql-server-5.1.49-sphinxse-1.10b_1.0-1_i386.deb

 You can remove it from your system anytime using: 

      dpkg -r mysql-server-5.1.49-sphinxse-1.10b

**********************************************************************
Save mysql-server-5.1.49-sphinxse-1.10b somewhere, e.g. /usr/src. Now you can install it:
$ sudo dpkg -i mysql-server-5.1.49-sphinxse-1.10b
and see it in the package list:
$ dpkg --list mysql-server-5.1.49-sphinxse-1.10b 
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Cfg-files/Unpacked/Failed-cfg/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                        Version                     Description
+++-===========================-===========================-======================================================================
ii  mysql-server-5.1.49-sphinxs 1.0-1                       mysql-5.1.49 + SphinxSE 1.10 beta
Launch mysql server at startup:
$ sudo cp support-files/mysql.server /etc/init.d/mysql
$ sudo chmod +x /etc/init.d/mysql
$ sudo update-rc.d mysql defaults
Copy configuration:
$ sudo cp support-files/my-medium.cnf /etc/my.cnf
If you had MySQL installed before, probably /etc/mysql/my.cnf file still exists with old configuration. In such case overwrite it:
$ sudo cp -f support-files/my-medium.cnf /etc/mysql/my.cnf
or make appropriate changes in it. Make MySQL binaries visible from everywhere. E.g. append the following line to ~/.bashrc:
export PATH=$PATH:/usr/local/mysql/bin:/usr/local/mysql/sbin
Now start MySQL daemon:
$ sudo /etc/init.d/mysql start
or, directly,
$ sudo /usr/local/mysql/bin mysqld_safe --user=mysql &
basedir, datadir etc. could be overriden whether in command line arguments, or in /etc/init.d/mysql itself. Now SPHINX should be in the engine list:
mysql> show engines \G
*************************** 1. row ***************************
      Engine: CSV
     Support: YES
     Comment: CSV storage engine
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 2. row ***************************
      Engine: SPHINX
     Support: YES
     Comment: Sphinx storage engine 0.9.9 ($Revision: 2391 $)
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 3. row ***************************
      Engine: MEMORY
     Support: YES
     Comment: Hash based, stored in memory, useful for temporary tables
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 4. row ***************************
      Engine: MyISAM
     Support: DEFAULT
     Comment: Default engine as of MySQL 3.23 with great performance
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 5. row ***************************
      Engine: MRG_MYISAM
     Support: YES
     Comment: Collection of identical MyISAM tables
Transactions: NO
          XA: NO
  Savepoints: NO
5 rows in set (0.00 sec)

UPDATE 18 AUGUST 2010

BTW, Ubuntu's standard mysql-server-5.1 package has a bug in \s (status) command: it doesn't show current database info(charset, name etc.). There is no such bug after installing from original source. And I'm still figuring out how to fix bug with DELETE key(it prints tilde("~") instead of removing a character). Occasionally, on the first compile a had got rid of it. But in the next install it appeared again. I suspect mysql-common(5.1.41-3ubuntu12.3) package. I believe, it'll be fixed, if I recompile mysql-server, but I've no spare time now.