#!/bin/sh
#----------------------------------------------------------------
# Define Global
#----------------------------------------------------------------
USER="xbmc"
HOST="XBMC"
HOME="/home/$USER"

blue="\\033[1;34m"
cyan="\\033[1;36m"
green="\\033[1;32m"
nc="\\033[0;39m"
red="\\033[1;31m"
white="\\033[1;37m"
yellow="\\033[1;33m"

export LANG=fr_FR.UTF-8
loadkeys fr-pc

#----------------------------------------------------------------
# Define Global
#----------------------------------------------------------------
function __welcome()
{
    clear
    echo "
    ********************************************
        W E L C O M E
    - - - - - - - - - - - -  - - - - - - - - - -
    1st part your disk using :
    cfdisk then mount it or use 
    sh $0 format

    then launch this ONE time only:

    sh $0 install

    Next you ill be promped when entering in CHROOT
    ******************************************** "

    __help

}

function __help()
{
    echo " Usage: sh $0 [ help | install | postinstall | extra ]

Available options:
    live
    help
    setup
    xbmc
    adduser
    systemd
    exit
    help        : display this help message
    format      : format /dev/sda1 to ext4
    install     : process the 1st step installation	
    postinstall : process the 2nd step installation 
    extra       : install some extra binaries
    extraDesktop: install Xorg xfce4 slim ....
    extraDev    : install some extra binaries for Development

"
}
function __format()
{
    #----------------------------------------------------------------
    # Create partition and format
    #----------------------------------------------------------------

    echo -e "$white Information : $nc Créer et formatter le disque sda ?$red (Attention perte des données) $nc"
    LISTE=("[o] oui" "[n] non")
    select CHOIX in "${LISTE[@]}" ; do
    case $REPLY in
        1|o)
            parted /dev/sda mklabel msdos y
            parted -a optimal /dev/sda mkpart primary ext4 0% 100%
            mkfs.ext4 /dev/sda1
        break
        ;;

        2|n)
            clear
        break
        ;;
	esac

done


}

function __mirrorlist()
{
    sed -i 6i'## France' /etc/pacman.d/mirrorlist
    sed -i 7i'Server = http://mir.archlinux.fr/$repo/os/$arch' /etc/pacman.d/mirrorlist # Config FR Mirror
    sed -i 8i'#' /etc/pacman.d/mirrorlist
}

function __live()
{
    clear
    __mirrorlist
    __format

    #----------------------------------------------------------------
    # Mount and Install
    #----------------------------------------------------------------
    mount /dev/sda1 /mnt && mkdir /mnt/{boot,home}

    #pacstrap /mnt {base,syslinux}
    pacstrap /mnt base base-devel sudo abs openssh vim
    #pacstrap /mnt base base-devel sudo zip unzip net-tools openssl openssh consolekit grub-bios subversion portaudio vim wget upower gstreamer0.10-base acpi acpid  pulseaudio pulseaudio-alsa alsa-plugins ntfs-3g nfs-utils dbus unrar p7zip lftp mtools dosfstools numlockx flac vorbis-tools xdg-user-dirs samba links  xorg-server xorg-xinit xorg-utils xorg-server-utils xterm xf86-video-intel libva-driver-intel xf86-video-nouveau nouveau-dri xf86-video-ati 

    #----------------------------------------------------------------
    # Get Setup
    #----------------------------------------------------------------

    #wget -P /mnt/ http://gutsblack.free.fr/xbmc/setup.sh
    #chmod 755 /mnt/setup.sh
    cp $0 /mnt
    chmod 755 /mnt/$0
    echo  "sh $0 setup" > /mnt/root/.profile
    echo  "sh $0 setup" > /mnt/root/.bash_profile
    echo  "sh $0 setup" > /mnt/root/.zprofile


    #----------------------------------------------------------------
    # Chroot System
    #----------------------------------------------------------------

    genfstab -p /mnt >> /mnt/etc/fstab
    clear
    echo -e "$white Lancer l'installation :$green sh $0 setup $nc"
    echo -e "$white Lancer depuis virtualbox :$green sh $0 virtualbox $nc"

    arch-chroot /mnt;
}



function __add_user()
{
	echo -n "# type a new user and press [ENTER]:"
	read USER
  
	echo "# Adding user $USER ..."
	useradd -m -s /bin/bash $USER
	passwd $USER
	usermod -G users,wheel,audio,video,lp,floppy,optical,storage,scanner,power,log $USER

	echo "
    Added user $USER

	Adding $USER to sudoers"

	echo "
    $USER ALL=(ALL) ALL
	$USER ALL=NOPASSWD: /usr/bin/pacman
	$USER ALL=NOPASSWD: /usr/bin/pacdiffviewer
	">> /etc/sudoers
}

function __setup()
{
    clear
    rm /root/{.zprofile,.bash_profile,.profile}


#----------------------------------------------------------------
# Config /etc/localtime
#----------------------------------------------------------------

ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime

#----------------------------------------------------------------
# Config /etc/hostname
#----------------------------------------------------------------
echo $HOST > /etc/hostname


#----------------------------------------------------------------
# Config /etc/vconsole.conf
#----------------------------------------------------------------

echo "KEYMAP=fr-latin9
FONT=
FONT_MAP=" > /etc/vconsole.conf


#----------------------------------------------------------------
# Config /etc/locale.conf
#----------------------------------------------------------------

echo "LANG=fr_FR.utf8
LC_COLLATE=C" > /etc/locale.conf

#----------------------------------------------------------------
# Config /etc/timezone
#----------------------------------------------------------------
echo "Europe/Paris" > /etc/timezone


#----------------------------------------------------------------
# Config /etc/locale.gen
#----------------------------------------------------------------

sed -i 's/^#fr_FR.UTF-8 UTF-8/fr_FR.UTF-8 UTF-8/' /etc/locale.gen
sed -i 's/^#fr_FR ISO-8859-1/fr_FR ISO-8859-1/' /etc/locale.gen
locale-gen


#----------------------------------------------------------------
# Root Password
#----------------------------------------------------------------

echo -e "$white Mot de passe root :$nc"
passwd


#----------------------------------------------------------------
# Config /etc.pacman.conf
#----------------------------------------------------------------

sed -i 's/^SyncFirst   = pacman/SyncFirst = pacman yaourt package-query pacman-color pyalpm namcap/' /etc/pacman.conf
sed -i 's/^#SigLevel = Optional TrustedOnly/SigLevel = Optional TrustedOnly/' /etc/pacman.conf
echo '[archlinuxfr]
Server = http://repo.archlinux.fr/$arch' >> /etc/pacman.conf

pacman -Syu --noconfirm yaourt

#----------------------------------------------------------------
# Config /root/.bashrc
#----------------------------------------------------------------

echo "alias ls='ls --color=auto'

#Alias Root
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'

PS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '" >> /root/.bashrc


#----------------------------------------------------------------
# Config /etc/sudoers
#----------------------------------------------------------------

sed -i 's/^# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/' /etc/sudoers


#----------------------------------------------------------------
# Config /etc/vimrc
#----------------------------------------------------------------

sed -i 16i"syntax on" /etc/vimrc # Config Vim

#----------------------------------------------------------------
# Config /etc/X11/xorg.conf.d/10-keyboard-layout.conf
#----------------------------------------------------------------
echo "Section \"InputClass\"
	Identifier	\"Keyboard Layout\"
	MatchIsKeyboard	\"yes\"
	MatchDevicePath	\"/dev/input/event*\"
	Option	\"XkbLayout\"	\"fr\"
	Option	\"XkbVariant\"	\"latin9\"
EndSection" > /etc/X11/xorg.conf.d/10-keyboard-layout.conf

    #----------------------------------------------------------------
    # Final Config
    #----------------------------------------------------------------
    #mkinitcpio -p linux

}

function __bootloader()
{
    clear
    echo -e "$white" "Install wich bootloader ? "

    #LISTE=("[o] oui" "[n] non")
    LISTE=("[y] syslinux" "[n] grub2")
    select CHOIX in "${LISTE[@]}" ; do
    case $REPLY in

        1|o|y)
            __bootloader_system syslinux
            clear
        break
        ;;

        2|n)
            __bootloader_system grub
            clear
        break
        ;;
        esac

    done
}
function __bootloader_system()
{
    if [[ "$1" = 'syslinux' ]]; then
        pacman -S --noconfirm syslinux
        # syslinux
        #vi /boot/syslinux/syslinux.cfg 
        sed -i 's/sda[1-9]/sda1/' /boot/syslinux/syslinux.cfg
        sed -i 's/TIMEOUT 50/TIMEOUT 5/' /boot/syslinux/syslinux.cfg
        syslinux-install_update -iam
    else
        pacman -S --noconfirm grub-bios
        # grub !
        grub-install --directory=/usr/lib/grub/i386-pc --target=i386-pc --boot-directory=/boot --recheck --debug /dev/sda
        sed -i 's/^GRUB_TIMEOUT=5/GRUB_TIMEOUT=0/' /etc/pacman.conf
        grub-mkconfig -o /boot/grub/grub.cfg
    fi
}
function __exit()
{
    #----------------------------------------------------------------
    # Exit Chroot System
    #----------------------------------------------------------------

    clear
    echo -e "$white Installation :$green terminé !$nc tapez $white exit $nc puis $white umount /mnt $nc et pour finir $white reboot $nc pour redémarrer :D"
    exit
}

function __add_xbmc()
{
    #----------------------------------------------------------------
    # install all bins:
    #----------------------------------------------------------------
    __extra xbmc

    #----------------------------------------------------------------
    # Create user and group xbmc
    #----------------------------------------------------------------

    groupadd xbmc
    useradd -m -g users -G audio,lp,optical,storage,video,wheel,games,power,xbmc -s /bin/bash xbmc

    # Get password
    echo -e "$white Mot de passe utilisateur (xbmc) :$nc"
    passwd xbmc

#----------------------------------------------------------------
# Config /home/xbmc/.bashrc
#----------------------------------------------------------------
echo "
#Alias xbmc
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
" > $HOME/.bashrc
sed -i "s|^PS1='[\u@\h \W]\$ '|PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] '|" $HOME/.bashrc
echo "PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] '" >> $HOME/.bashrc
chown xbmc:users $HOME/.bashrc


#----------------------------------------------------------------
# Config /home/xbmc/.config/user-dirs.dirs
#----------------------------------------------------------------

mkdir $HOME/.config
chown xbmc:users $HOME/.config
touch $HOME/.config/user-dirs.dirs
echo 'XDG_DESKTOP_DIR="$HOME/Bureau"
XDG_TEMPLATES_DIR="$HOME/Travail"
XDG_PUBLICSHARE_DIR="$HOME/Public"
XDG_DOCUMENTS_DIR="$HOME/Document"
XDG_MUSIC_DIR="$HOME/Musique"
XDG_PICTURES_DIR="$HOME/Image"' >> $HOME/.config/user-dirs.dirs

mkdir $HOME/Bureau
mkdir $HOME/Travail
mkdir $HOME/Public
mkdir $HOME/Document
mkdir $HOME/Musique
mkdir $HOME/Image

#mkdir $HOME/{Bureau,Travail,Public,Document,Musique,Image}
#chown xbmc:users $HOME/{Bureau,Travail,Public,Document,Musique,Image,.config/user-dirs.dirs}

chown xbmc:users $HOME/Bureau
chown xbmc:users $HOME/Travail
chown xbmc:users $HOME/Public
chown xbmc:users $HOME/Document
chown xbmc:users $HOME/Musique
chown xbmc:users $HOME/Image
chown xbmc:users $HOME/.config/user-dirs.dirs

#----------------------------------------------------------------
# Config /etc/samba/smb.conf
#----------------------------------------------------------------

echo "[global]
workgroup = Net
server string = XBMC
hosts allow = 192.168.0.
printcap name = lpstat
load printers = yes
printing = cups
guest account = xbmc
log file = /var/log/samba/log.%m
max log size = 50
security = share
socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=16384
oplocks = False
level2 oplocks = true
read prediction = yes
local master = no
os level = 33
dns proxy = no
unix charset = UTF-8
dos charset = CP850
wins support = no
 
[homes]
comment = Home Directories
browseable = no
writable = no
 
[HOME XBMC]
comment = no comment
path = /home/xbmc/
public = yes
writable = yes
printable = no
 
[XBMC CONFIG]
comment = no comment
path = /home/xbmc/.xbmc
public = yes
writable = yes
printable = no" >> /etc/samba/smb.conf


#----------------------------------------------------------------
# Config /lib/systemd/system/xbmc.service
#----------------------------------------------------------------

echo "[UNIT]
Description = Starts instance of XBMC using xinit
After = syslog.target
 
[Service]
User = xbmc
Group = xbmc
Type = simple
ExecStart = /usr/bin/xinit /usr/bin/xbmc-standalone -- :0
 
[Install]
WantedBy = multi-user.target" >> /lib/systemd/system/xbmc.service

#----------------------------------------------------------------
# Config polkit-1
#----------------------------------------------------------------
echo "[Actions for xbmc user]
Identity=unix-user:xbmc
Action=org.freedesktop.devicekit.power.*;org.freedesktop.consolekit.system.*
ResultActive=yes
ResultAny=yes
ResultInactive=no" >> /var/lib/polkit-1/localauthority/50-local.d/xbmc.pkla



#----------------------------------------------------------------
# Install XBMC
#----------------------------------------------------------------

clear
echo -e "$white" "Information :" "$nc" " XBMC classique ou PVR ?"

LISTE=("[c] Classique" "[p] PVR")
select CHOIX in "${LISTE[@]}" ; do
case $REPLY in

	1|c)
		echo -e "$white" "Installation :" "$nc" " XBMC"
		pacman -S --noconfirm xbmc
		clear
	break
	;;

	2|p)
		echo -e "$white" "Installation :" "$nc" " XBMC PVR "
		yaourt -S --noconfirm xbmc-eden-pvr-git tvheadend-git linuxtv-dvb-apps w_scan
		systemctl enable tvheadend.service

		clear
	break
	;;
	esac

done
}


function __system_d()
{
    clear
    pacman -Syu --noconfirm systemd systemd-sysvcompat systemd-arch-units
    pacman -Syu --noconfirm python2-cairo python2-dbus

    systemctl enable dbus.service
    systemctl enable acpid.service
    systemctl enable smbd.service nmbd.service
    systemctl enable bluetooth.service
    systemctl enable sshd.service
    systemctl enable xbmc.service
    #systemctl enable dhcpcd@eth0.service
    systemctl enable dhcpcd@.service


    #echo -e "$white" "Install system-D ?"

    ##LISTE=("[o] oui" "[n] non")
    #LISTE=("[y] yes" "[n] no")
    #select CHOIX in "${LISTE[@]}" ; do
    #case $REPLY in

    #    1|o|y)
    #        #----------------------------------------------------------------
    #        # Delete SysVinit And Install SystemD
    #        #----------------------------------------------------------------
    #        pacman -Rsn --noconfirm initscripts sysvinit
    #        pacman -Syu --noconfirm systemd systemd-sysvcompat systemd-arch-units
    #        pacman -Syu --noconfirm python2-cairo python2-dbus
    #        #----------------------------------------------------------------
    #        # Enable SystemD Service
    #        #----------------------------------------------------------------

    #        systemctl enable dbus.service
    #        systemctl enable acpid.service
    #        systemctl enable smbd.service nmbd.service
    #        systemctl enable bluetooth.service
    #        systemctl enable sshd.service
    #        systemctl enable xbmc.service
    #        #systemctl enable dhcpcd@eth0.service
    #        systemctl enable dhcpcd@.service

    #    break
    #    ;;

    #    2|n)
    #        clear
    #    break
    #    ;;
    #    esac

    #done
    #clear

}


function __extra()
{
    if [[ $# = 0 ]]; then
        yaourt -S fu-git bleachbit-cli --noconfirm

        ## cleaean all cleaners
        # bleachbit -c `bleachbit -l | xargs echo`
        return
    fi
    if [[ "$1" = 'xbmc' ]]; then
        pacman -Syu  --noconfirm zip unzip net-tools openssl consolekit subversion portaudio wget upower gstreamer0.10-base acpi acpid  pulseaudio pulseaudio-alsa alsa-plugins ntfs-3g nfs-utils dbus unrar p7zip lftp mtools dosfstools numlockx flac vorbis-tools xdg-user-dirs samba links  xorg-server xorg-xinit xorg-utils xorg-server-utils xterm xf86-video-intel libva-driver-intel xf86-video-nouveau nouveau-dri xf86-video-ati xf86-video-vesa
    fi
    if [[ "$1" = 'xorg' ]]; then
        pacman -Syu xorg-server xorg-xinit xorg-utils xorg-server-utils  xf86-video-vesa awesome --noconfirm 
        echo "#! /bin/sh
exec awesome
#exec startxfce4
#exec dwm
#exec startfluxbox
#exec fvwm2
#exec gnome-session
#exec openbox-session
#exec startkde
#exec startlxde
#exec enlightenment_start" > /root/.xinitrc


    fi
    if [[ "$1" = 'virtualbox' ]]; then
        pacman -Syu virtualbox-guest-utils --noconfirm
    fi
    if [[ "$1" = 'desktop' ]]; then
        __help

        pacman -Syu xorg-server xorg-xinit xorg-utils xorg-server-utils  xf86-video-vesa --noconfirm
        #pacman -S xfce4 firefox slim --noconfirm

        echo "#! /bin/sh
exec startxfce4
#exec awesome
#exec dwm
#exec startfluxbox
#exec fvwm2
#exec gnome-session
#exec openbox-session
#exec startkde
#exec startlxde
#exec enlightenment_start" > /root/.xinitrc

        sed -i 's|@crond|@crond @slim|' /etc/rc.conf
    fi
}

function main()
{
    if [[ $# = 0 ]]; then
        __welcome
    fi
    if [[ $# = 1 ]]; then
        if [[ "$1" = 'help' ]]; then
            __help
        fi
        if [[ "$1" = 'format' ]]; then
            __format
        fi
        if [[ "$1" = 'live' ]]; then
            __live
        fi
        if [[ "$1" = 'setup' ]]; then
            __setup
            __bootloader
            __system_d
            __extra
            #__extra desktop
        fi
        if [[ "$1" = 'xbmc' ]]; then
            __add_xbmc
        fi
        if [[ "$1" = 'adduser' ]]; then
            __add_user
        fi
        if [[ "$1" = 'systemd' ]]; then
            __system_d
        fi
        if [[ "$1" = 'extra' ]]; then
            __extra
        fi
        if [[ "$1" = 'desktop' ]]; then
            __extra desktop
        fi
        if [[ "$1" = 'virtualbox' ]]; then
            __setup
            __bootloader_system syslinux
            __system_d
            __extra
            #__extra desktop
            __extra xorg
            __extra virtualbox
            __exit
            umount /mnt;
            reboot;
        fi
        if [[ "$1" = 'exit' ]]; then
            __exit
        fi
    fi

}

main $*
