#!/bin/bash

if [ "$(id -u)" = 0 ]; then

    mkdir -p /var/db/repos /var/cache/{distfiles,packages}
    chown -hR portage: /var/cache/{distfiles,packages}
    find /var/db/repos -type d | xargs -I {} chmod 755 {}
    find /var/db/repos -type f | xargs -I {} chmod 644 {}

    find /srv/http -type d | xargs -I {} chmod 755 {}
    find /srv/http -type f | xargs -I {} chmod 644 {}
    if [ -d /var/lighttpd ]; then
        find /var/lighttpd -type d | xargs -I {} chmod 755 {}
        find /var/lighttpd -type f | xargs -I {} chmod 644 {}
    fi

    chmod 600 /etc/{gshadow,shadow}
    chmod 644 /etc/{group,passwd}

    if [ -d /etc/ssh ]; then
        chmod 755 /etc/ssh
        chown root:root /etc/ssh

        [ -f /etc/ssh/sshd_config ] && chmod 644 /etc/ssh/sshd_config
        [ -f /etc/ssh/ssh_config ] && chmod 644 /etc/ssh/ssh_config

        for keyfile in /etc/ssh/ssh_host_*_key; do
            [ -f "$keyfile" ] && chmod 600 "$keyfile" && chown root:root "$keyfile"
        done

        for pubfile in /etc/ssh/ssh_host_*_key.pub; do
            [ -f "$pubfile" ] && chmod 644 "$pubfile" && chown root:root "$pubfile"
        done
    fi

    chmod 440 /etc/sudoers
    chmod 700 /etc/ssl/private
    chmod 644 /etc/ssl/certs/*
    chmod 755 /var/log
    find /var/log -type f | xargs -I {} chmod 640 {}
    chmod 1777 /tmp /var/tmp
    chmod 755 /var/spool
    chmod 755 /var/lib
fi

chmod 600 "$HOME/.bash_history"

if [ -d "$HOME/.ssh" ]; then
    find "$HOME/.ssh" -type d | xargs -I {} chmod 700 {}
    find "$HOME/.ssh" -type f | xargs -I {} chmod 600 {}
fi

if [ -d "$HOME/.gnupg" ]; then
    find "$HOME/.gnupg" -type d | xargs -I {} chmod 700 {}
    find "$HOME/.gnupg" -type f | xargs -I {} chmod 600 {}
fi
