Wednesday, March 14, 2012

satellite.sh - sync favorite folders using pen-drive

#!/bin/bash
# save it as '~/bin/satellite.sh'

ZIP_DRIVE_NAME="KING1GB"

INVALID="usage: $0  < upload | download >"
UP="UPLOAD"
DOWN="DOWNLOAD"

if [ $# -ne 1 ];then
    echo "$INVALID"
    exit 1
fi

arg=$1
a_string=""
a_string_common="Press Enter to continue or Ctrl+C to exit: "
text=""

case "$arg" in
upload|\>)
    arg=$UP
    a_string="UPLOADING\nwill overwrite SATELLITE \033[35G"${a_string_common}
    ;;
download|\<)
    arg=$DOWN
    a_string="DOWNLOADING\nwill overwrite BASE \033[35G"${a_string_common}
    ;;
*)
    arg=NONE
    echo "$INVALID"
    exit 1
esac

echo -ne "${a_string}"
read text

# ---- BLOCK-START ----
# add path to both arrays
# and basename of the path must be a folder

SATPATH=/media/${ZIP_DRIVE_NAME}/.A-BOX
if [ ! -d ${SATPATH} ];then
    SATPATH=/media/${USER}/${ZIP_DRIVE_NAME}/.A-BOX
    if [ ! -d ${SATPATH} ];then
        echo "remote path '$SATPATH' does not exit, check usb"
        exit 2
    fi
fi
 

path_satellite[1]="$SATPATH/bin"
path_satellite[2]="$SATPATH/learning"
path_satellite[3]="$SATPATH/scripting"
path_satellite[4]="$SATPATH/Wallpapers"
#
path_base[1]="$HOME/bin"
path_base[2]="$HOME/Documents/learning"
path_base[3]="$HOME/Documents/turbo/scripting"path_base[4]="$HOME/Pictures/Wallpapers"
#
# ---- BLOCK-END ----

#
# check that both arrays contains same number of elements
#
if [ ${#path_satellite[@]} -ne ${#path_base[@]} ];then
    echo -e "mismatch detected in ${0}\nkindly verify both arrays, exiting"
    exit 1
fi

total=${#path_base[@]}
echo "total: $total"

#
# check that order of elements in both arrays are same
#
counter=1
while [ $counter -le $total ]
do
    temp_sate=$(basename ${path_satellite[$counter]})
    temp_base=$(basename ${path_base[$counter]})

    if [ "${temp_sate}" != "${temp_base}" ];then
        echo "satellite: ${temp_sate}"
        echo "base     : ${temp_base}"
        echo "above paths does not match in ${0}, kindly check and rerun"
        exit 1
    fi
    counter=$(expr $counter + 1)
done

#
# chech if local copy of satellite.sh is latest
#
f_remote="$SATPATH/bin/satellite.sh"
f_local="$HOME/bin/satellite.sh"

if [ -f "${f_remote}" ];then

    skip_check="no"

    script_remote=$(stat ${f_remote} | grep "Modify")
    script_remote=$(echo ${script_remote:8:19} | sed 's/[- :]//g')

    script_local=$(stat ${f_local} | grep "Modify")
    script_local=$(echo ${script_local:8:19} | sed 's/[- :]//g')

    cur_timestamp=$(date +"%Y%m%d%H%M%S")

    echo "remote: ${script_remote}"
    echo "local : ${script_local}"

    #
    # got this error when run 'satellite.sh upload' on ubuntu 12.04
    # followed by running 'satellite.sh download' on fedora 16
    # on fedora 16 timestamp of /media/SATELLITE/.A-BOX/satellite.sh was cur+05:30
    #
    if [ "${script_remote}" -gt "${cur_timestamp}" ];then
        echo "remote script timestamp is set to future !!! could be time-setting problem !!!"
        echo -n "do you want to SKIP timestamp check !!! : "
        read choice

        if [ "$choice" = "y" -o "$choice" = "Y" ];then
            echo "skipping timestamp check"
            skip_check="yes"
        fi
    fi


    if [ "${script_remote}" -gt "${script_local}" -a "$skip_check" = "no" ];then
        cp -f ${f_remote} ${f_local}
        echo "local copy was outdated, hence updated"
        echo "re-run: ${0}"
        exit 1
    fi
fi


RSYNC_CMD="-av --delete --exclude=.metadata"

if [ "$arg" = "UPLOAD" ];then
    for (( x=1; x<=$total; x++))
    do
        [ ! -d ${path_satellite[x]} ] && mkdir -p ${path_satellite[x]}
        echo -e "\033[37;42;1m==> syncing\033[35G`basename ${path_base[x]}/`\033[m"
        #rsync -av --delete --exclude=".metadata" ${path_base[x]}/ ${path_satellite[x]}
        rsync ${RSYNC_CMD} ${path_base[x]}/ ${path_satellite[x]}
    done

elif [ "$arg" = "DOWNLOAD" ];then
    for (( x=1; x<=$total; x++))
    do
        [ ! -d ${path_base[x]} ] && mkdir -p ${path_base[x]}
        echo -e "\033[37;42;1m==> syncing\033[35G`basename ${path_satellite[x]}`\033[m"
        #rsync -av --delete --exclude=".metadata" ${path_satellite[x]}/ ${path_base[x]}
        rsync ${RSYNC_CMD} ${path_satellite[x]}/ ${path_base[x]}

    done

else
    echo "invalid option"
    exit 1
fi

echo -e "\033[;44;1m==> syncing\033[35GDONE\033[m"



#------------ END ------------



SATELLITE is the name of my pen-drive
run './satellite.sh upload' or './satellite.sh \>' to sync data to pen-drive
and './satellite.sh download' or './satellite.sh \<' to sync data on machine from pen-drive

it helps in syncing data, if work on different machines/laptops and need to carry personal/required folders with you all time.

before starting work use 'download' after finishing work 'upload' to SATELLITE.


Friday, December 9, 2011

time delay routine in C

/*
 * filename : counter.c
 * date     : 09-12-2011
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char default_msg[] = "counter will expire in following seconds";

int main(int argc, char* argv[])
{
    char *msg = default_msg;
    int delay = 0, hour, min, sec, days;
    int i;

    days = hour = min = sec = 0;

    switch (argc)
    {
        case 3:
            msg = argv[2];
        case 2:

            for (i=0; i < strlen(argv[1]); i++)
            {
                if (!isdigit(argv[1][i]))
                {
                    printf("invalid digit '%c' at position %d in argument\n", argv[1][i], i);
                    return -1;
                }
            }
            delay = atoi(argv[1]);
            break;
        default:
            printf("invalid number of arguments\n"
                    "usage: %s [\"message\"]\n", argv[0]);
            fflush(stdout);
            return -1;
    }

    /*
     * calculate exact time in hh:mm:ss entered for delay-sec
     */
    sec  = delay % 60;
    min  = (delay / 60) % 60;
    hour = (delay / 3600) % 24;
    days = delay / (3600 * 24);

    printf("MSG: %s - DAYS: %d, %d:%d:%d\n", msg, days, hour, min, sec);
    for (i=delay; i >= 0 ; i--)
    {
        printf("\rcounter: %d", i);
        fflush(stdout);        sleep(1);
    }
    printf("\n");

    return 0;
}


/*
* compile with gcc
* gcc counter.c -o COUNTER
* ./COUNTER 15
* ./COUNTER 97405
*/

Friday, November 11, 2011

my ~/.vimrc file

set hlsearch
set nu
set ignorecase
set expandtab
set shiftwidth=4
set softtabstop=4

if has ("autocmd")
    autocmd BufRead *.file set tw=150
    autocmd BufRead *.prvc set nobackup nowritebackup foldmethod=indent fdo=insert
    filetype plugin indent on
    au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
endif


For gVim, following options can be added to "_vimrc" file
at path: C:\Users\\_vimrc

set noswf

if has("gui_running")
    if has("gui_win32")
        set guifont=Fixedsys:h11
    endif
endif


# other options:
# gui_gtk2 / gui_macvim / gui_gtk3 / gui_win32
 



Wednesday, November 9, 2011

Create Bootable Fedora USB stick from ISO image on any Linux distro


Fedora-15-x86_64-Live-KDE.iso,
usb-stick (/dev/sdb1) 8GB having label SATELLITE (1GB is enough),
and syslinux command.

Following are the steps:
# mkdir /mnt/{iso,usb}
# mount -t iso9660 /home/user/Fedora-15-x86_64-Live-KDE.iso /mnt/iso
# mount /dev/sdb1 /mnt/usb
NOTE: /dev/sdb1 is my usb-stick
# cp -rv /mnt/iso/* /mnt/usb/
# syslinux --install -d EFI/boot/ /dev/sdb1
used '-d EFI/boot/' because vmlinuz and initrd image file exist in this folder wrt to root of usb ie /mnt/usb
otherwise need to edit their paths accordingly in syslinux.cfg.
# cd /mnt/usb/EFI/boot
# cp isolinux.cfg syslinux.cfg
edit syslinux.cfg and edit 'root' parameter of kernel
root=LABEL=SATELLITE
eg,
label linux0
   menu label Boot
   kernel vmlinuz0
   append initrd=initrd0.img root=LABEL=SATELLITE rootfstype=auto ro liveimg rd.luks=0 rd.md=0 rd.dm=0


Can Test it with qemu or qemu-system-x86_64:
# qemu-system-x86_64 -hda /dev/sdb1 -m256 -vga std

If boot successfully, just reboot the system and boot it from usb.

NOTE: label can be set using command: e2label /dev/sdb1 SATELLITE

Sunday, March 27, 2011

xorg.conf of RHEL 5.0


# Xorg configuration created by pyxf86config
Section “ServerLayout”
Identifier “Default Layout”
Screen 0 “Screen0” 0 0
InputDevice “Keyboard0” “CoreKeyboard”
InputDevice “Synatics” “CorePointer”
EndSection

Section “InputDevice”
Identifier “Keyboard0”
Driver “kbd”
Option “XkbModel” “pc105”
Option “XkbLayout” “us”
EndSection

Section “InputDevice”
Identifier “Synaptics”
Driver “synaptics”
Option “Device” “/dev/input/mice”
Option “Protocol” “auto-dev”
Option “Emulate3Buttons” “yes”
EndSection

Section “Device”
Identifier “Videocard0”
Driver “via”
EndSection

Section “Screen”
Identifier “Screen0”
Driver “Videocard0”
Monitor “Monitor0”
DefaultDepth 24

SubSection “Display”
Viewport 0 0
Depth 24
Modes “1024x768” “800x600”
EndSubSection
EndSection

Section “Monitor”
Identifier “Monitor0”
HorizSync 31.5 – 48.5
VertRefresh 59.0 – 75.0
EndSection
# ---- END ----

Tuesday, March 1, 2011

know your home folder in LINUX

[From wikipedia]

A Home directory is a file system directory on a multi-user operating system containing files for a given user of the system.

The benefits of home folder are :
1. Separating user data from system-wide data avoids redundancy and makes backups of important files relatively simple.
2. user himself, person or program (trojan, virus etc) having user's privileges only be able to alter the files in the user's home directory and some files belonging to workgroups the user is a part of, but not actual system files.
[end]

In Linux,

Tilde '~' represent the user's home folder, that is '/home/user'.

To go back to user's home folder from any location simply enter 'cd' command.

To know the present working directory use 'pwd' command.



On using 'ls -a' command in the user's home folder (depending on version of Linux) following file/files can be found:
.bashrc
.profile

.bash_profile



These files can be used to override the global settings and these settings will only applicable to the current user (that means settings for all the other users remain unchanged). At logon time, bash shell read these files, that means any changes made to them will reflect when you logged on next time. But you can also made those changes to current terminal (without logout) only by manually executing them, for example if changed made to .bashrc, command will be '. ~/.bashrc'.

Following are some important settings:

1. Environment variables

2. Shell's display prompt

3. Aliases of commonly used commands



Environment variable can be view using 'env' command. You can create your own or can edit existing environment variable. While editing existing environment variable make sure you should always append to it with colon ':' or some application/program may not work.

for example to export new environment variable DOC, representing /home/user/Documents/mystuff.
open the above mentioned file and add this line.
export DOC=/home/user/Documents/mystuff
OR more appropriate approach.
export DOC=$HOME/Documents/mystuff

In the above example $HOME is already existing env var and DOC is new created. It can be check using command 'echo $DOC' ie $DOC can be used in place of ~/Documents/mystuff.


You can customize the prompt displayed in terminal by changing 'PS1' environment variable. for example is you do not want absolute path to be shown in prompt then,
PS1=”\u@\h:\W$ “

[NOTE capital 'W', will show current folder while small 'w' show absolute path]
execute it on terminal to see the effect, if want it permanent, copy it to one of the above mentioned file.

If your terminal support, you can have colorful prompt. for example,
PS1=”\033[32;1m\u@\h\033[m:\033[34;1m\W\033[m$ ”


Alias can be created for commonly used long commands, like
if you frequently use 'ls' command to print the result in long format, reverse sorted with time 'ls -lrt', make following entry in the mentioned file.
alias ll='ls -lrt'
now you can use 'll' command instead of 'ls -lrt'

NOTE:
1. As a precaution you can create a new normal user to test the commands mentioned above or you may end up with a non-workable login.
2. Always remember to keep backup before editing any file. Precaution is better than cure.

Wednesday, December 1, 2010

enable terminal color in Guake

In guake type:
$ echo $TERM
$ dumb

then,
vim ~/.bashrc
export TERM=xterm

The above mentioned problem occur in ubuntu 10.10